/* $Header:tee.c 12.0$ */
/* $ACIS:tee.c 12.0$ */
/* $Source: /ibm/acis/usr/src/bin/RCS/tee.c,v $ */

#ifndef lint
static char *rcsid = "$Header:tee.c 12.0$";
#endif

#ifndef lint
static char *sccsid = "@(#)tee.c	5.4 (Berkeley) 12/14/85";
#endif
/*
 * tee-- pipe fitting
 */

#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <stdio.h>
#include <errno.h>

#define	BUFSIZ	8192
int openf[20] = { 1 };
int n = 1;
int t = 0;
int aflag;

char in[BUFSIZ];

char out[BUFSIZ];

extern errno;
long	lseek();

main(argc,argv)
char **argv;
{
	int register r,w,p;
	struct stat buf;
	while(argc>1&&argv[1][0]=='-') {
		switch(argv[1][1]) {
		case 'a':
			aflag++;
			break;
		case 'i':
		case 0:
			signal(SIGINT, SIG_IGN);
		}
		argv++;
		argc--;
	}
	fstat(1,&buf);
	t = (buf.st_mode&S_IFMT)==S_IFCHR;
	if(lseek(1,0L,1)==-1&&errno==ESPIPE)
		t++;
	while(argc-->1) {
		if(aflag) {
			openf[n] = open(argv[1],O_WRONLY|O_APPEND|O_CREAT,0666);
		} else {
			openf[n] = open(argv[1],O_WRONLY|O_TRUNC|O_CREAT,0666);
		}
		if(openf[n] < 0) {
			fprintf(stderr, "tee: cannot open %s\n", argv[1]);
		} else {
			n++;
			stat(argv[1],&buf);
			if((buf.st_mode&S_IFMT)==S_IFCHR)
				t++;
		}
		argv++;
	}
	r = w = 0;
	for(;;) {
		for(p=0;p<BUFSIZ;) {
			if(r>=w) {
				if(t>0&&p>0) break;
				w = read(0,in,BUFSIZ);
				r = 0;
				if(w<=0) {
					stash(p);
					exit(0);
				}
			}
			out[p++] = in[r++];
		}
		stash(p);
	}
}

stash(p)
{
	int k;
	int i;
	int d;
	d = t ? 16 : p;
	for(i=0; i<p; i+=d)
		for(k=0;k<n;k++)
			write(openf[k], out+i, d<p-i?d:p-i);
}
