/*
          Tee - Create a T junction in a pipe.

          Original effort by Fabio Rossetti. Inspired by the tee program
          by Gary Brant found on <>< 179.

	  (c) 1989 by Fabio Rossetti

	  To compile under Lattice C v5.0x use:

		lc -O -v -cus tee
		blink lib:cres.o tee.o to tee lib lib:a.lib lib:lc.lib sd nd

*/

#include <exec/types.h>
#include <exec/memory.h>
#include <exec/libraries.h>

#include <libraries/dos.h>
#include <libraries/dosextens.h>
#include <libraries/arpbase.h>

#include <arpfunctions.h>

#include <proto/exec.h>
#include <proto/dos.h>

#define BFSIZE 256

struct ArpBase *ArpBase;
BPTR Stdout,Stdin,fh;
struct Process *Pr;
TEXT *Buf;		

/* Trick to keep code down to size */
VOID MemCleanup()
{
}

/* as above */
VOID _main(Line)
STRPTR Line;

{
	
	STRPTR argv;
	REGISTER ULONG count;

	Pr = (struct Process*)FindTask(NULL);
	
	if(!(ArpBase = (struct ArpBase*)OpenLibrary(ArpName,ArpVersion))){
			Pr->pr_Result2=ERROR_INVALID_RESIDENT_LIBRARY;
			exit(RETURN_FAIL);
			}
	
	/* parse command line */

		argv =  NULL;

	while(*Line > ' ')
		++Line;

	/* don't need argc */
	if (GADS(++Line,
		strlen(Line),
		"Usage: Tee <Stdin >Stdout Filename",
		&argv,
		"FILE/A") <= 0) {
			Puts(argv);
			CloseLibrary((struct Library *)ArpBase);
			exit(RETURN_WARN);
			}

	Stdout = Output();
	Stdin = Input();

	if (!(Buf=(ArpAlloc(BFSIZE)))) {;
			Puts ("Error: No memory");
			Pr->pr_Result2 = ERROR_NO_FREE_STORE;
			exit(RETURN_FAIL);
			}
	if (!(fh  = ArpOpen(argv,MODE_NEWFILE))) {
			Puts ("Error: Can't open file.");
			Pr->pr_Result2 = ERROR_OBJECT_NOT_FOUND;
			exit(RETURN_ERROR);
			}
	/* Now copy streams */	
	while (count = Read(Stdin,Buf,BFSIZE)){
	Write(Stdout,Buf,count);
	Write(fh,Buf,count);
	}

	CloseLibrary((struct Library *)ArpBase);

}
