/* TEE - UNIX filter --  it takes one parm, output filename, and output  */
/* is directed to standard output, and the output file named in the cmd  */
/* line.                                                                 */

#include <stdio.h>
#include <fcntl.h>
#include <stat.h>

#define	TRUE	1
#define	FALSE	0
#define LINESIZE BUFSIZ

static	char	OBufr[BUFSIZ];		/* output file buffer required	*/

static	char	*Program[]	= { "S. Leoce	*NIX(tm) TEE filter"
				    "V1.0 R1.0 SVCLVL 0 - VA @PSJ  "};

#include "b:cmdline.c"

main (argc, argv)
int argc;
char *argv[];

{
	short unsigned int LineOption = FALSE;

	FILE  *OFile;
	int   OF_Hndl;		/* file handle */

	static char *usage = "usage: tee [/ahiv] file [< stdin] [> stdout]";

	long unsigned register int lines = 0;
	auto char line [LINESIZE];

	auto short append = FALSE;    /* default options processing */
	auto short count  = FALSE;
	auto short header = FALSE;	

	if (argc < 2) {
		fprintf(stderr,"%s\n",usage);
		_exit (0x10);
	}

  	opterr = FALSE;
	while ((LineOption = getopt(argc, argv, "ahiv")) != EOF)
		switch (LineOption)	{
			case '?':
				fprintf(stderr,"tee: illegal option\n");
				_exit(0x04);
			case 'i':
				fprintf(stderr,"tee: i unsupported in DOS\n");
				break;
			case 'a':
				append = TRUE;
				break;
			case 'v':
				count  = TRUE;
				break;
			case 'h':
				header = TRUE;
				break;
		}

	if (argv[optind] == NULL) {
		fprintf(stderr, "%s\n",usage);
		_exit (0x10);
	}
	if (append) {
		if ((OFile = fopen(argv[optind], "a")) == NULL)
			_exit(perror(strcat("Can't open ",strupr(argv[optind]))));
	}
	else {
		if ((OF_Hndl = creat(argv[optind],O_TEXT|S_IWRITE|S_IREAD)) == -1)
			_exit(perror(strcat("Can't create ",strupr(argv[optind]))));
       		
       		if ((OFile = fdopen(OF_Hndl, "w")) == NULL)
       			_exit(perror("Can't connect device "));
	}
	while (fgets(line, LINESIZE, stdin) != NULL) {
		fprintf (OFile, "%s", line);
		printf ("%s", line);

		lines++;
	}
	if (header)
		fprintf(OFile,"\n/*EOF %7ld RCD\n", lines);

	fflush (OFile);
	fclose (OFile);
	if (count)
		fprintf(stderr, "tee: processed lines %7ld\n", lines);

	_exit (0);
}