/* UNIX like tee program. Kees Lemmens; Dec. 1992

   This program can be used to duplicate your session to an other file
   or device on a multitasking ATARI ST (MINT). It can not work on a
   normal ATARI, because it needs two separate processes !
   It behaves just like the UNIX tee utility.

   Bugs/remarks:
-  Some programs - like tcsh - send a signal TTOU when a foreign process
   attempts to write to their tty. This causes the foreign process to be
   suspended. To avoid this problem the tee program has to ignore such
   signals.
-  Stderr is not copied to the other screen and also terminal sessions
   by means of kermit or tip cannot be duplicated !!

   Any questions or suggestions about this program can be send to:
   lemmens@dv.twi.tudelft.nl
*/

#include <stdio.h>
#include <fcntl.h>	/* O_CREAT etc. */
#include <stdlib.h>
#include <signal.h>
#include "ux_misc.h"

void fatal(char *txt)
{	fputs("TEE: ",stderr);
	fputs(txt,stderr);
	exit(1);
}
/*
void do_write(char *output,char *mode)
{	FILE *dupout;
	char c;

	if((dupout=fopen(output,mode)) < 0)
		fatal("Can't open file");

	setbuf(stdin,NULL);
	setbuf(dupout,NULL);
	while((c=fgetc(stdin)), !feof(stdin))
	{	fputc(c,stdout);
		fputc(c,dupout);
	}
	fclose(dupout);
}
*/
void do_write(char *output,int mode)
{	int dupout,hstdin,hstdout;
	char c,cr='\15';

	if((dupout=open(output,O_WRONLY|mode)) < 0)
		fatal("Can't open file");
    hstdin=fileno(stdin);
	hstdout=fileno(stdout);
	while(read(hstdin,&c,1) > 0) /* until eof */
	{	write(hstdout,&c,1);
		write( dupout,&c,1);
		if(c == '\n')
		{	write(hstdout,&cr,1);
			write( dupout,&cr,1);
		}
	}
	close(dupout);
}

void usage(void)
{	puts("\nUsage: tee [-a] <file|device>");
	exit(1);
}

void main(int argc,char *argv[]) 
{	int mode=O_CREAT|O_TRUNC;

	if(argc<2)	usage();

	/* ignore signal [Attempted write to foreign tty] */

	signal(SIGTTOU,SIG_IGN);

	while(--argc>0)			/* parse options */
	{	if(*argv[1]=='-')
		{	switch(*(++argv[1]))
			{	case 'a':	mode = O_APPEND;	break;
				default :	usage();
			}
			++argv;
		}
	}	
	ux2dos(argv[1]);	/* convert slashes */
	do_write(argv[1],mode);
}
