/*
 * cp oldfile newfile
 */

main(argc,argv)
char **argv;
{
	int buf[256];
	int fold, fnew, n, ct, tell;
	char *p1, *p2, *bp;
	int mode;

	tell = 0;
	if(argc == 4 && argv[1][0] == '-' && argv[1][1] == 't') {
		argc--;
		argv++;
		tell = 1;
	}
	if(argc != 3) {
		write(1, "Usage: cp oldfile newfile\n", 26);
		exit(8);
	}
	if((fold = open(argv[1], 0)) < 0) {
		write(1, "Cannot open old file.\n", 22);
		exit(8);
	}
	fstat(fold, buf);
	mode = buf[2];
/* Is destination a directory? */
	if (stat(argv[2], buf+50)>=0 && (buf[52]&060000)==040000) {
		p1 = argv[1];
		p2 = argv[2];
		bp = buf+100;
		while(*bp++ = *p2++);
		bp[-1] = '/';
		p2 = bp;
		while(*bp = *p1++)
			if(*bp++ == '/')
				bp = p2;
		argv[2] = buf+100;
	}
	if (stat(argv[2], buf+50) >= 0) {
		if (buf[0]==buf[50] && buf[1]==buf[51]) {
			write(1, "Copying file to itself.\n", 24);
			exit(8);
		}
	}
	if ((fnew = creat(argv[2], mode)) < 0) {
		write(1, "Can't create new file.\n", 23);
		exit(8);
	}
	while(n = read(fold,  buf,  512)) {
	if(n < 0) {
		write(1, "Read error\n", 11);
		exit(8);
	} else
		if(write(fnew, buf, n) != n){
			write(1, "Write error.\n", 13);
			exit(8);
		}
		ct++;
	}
	if(tell) {
		conf(ct, 6, buf);
		buf[3] = '\n';
		write(1, buf, 7);
	}
	exit(0);
}

conf(n,width,buf) 
	char	*buf;
{
	auto	i,a;

	i = width;
	while(i--)	buf[i] = ' ';

	buf[(a = n/10)?conf(a,--width,buf):--width] = n%10 + '0';

	return(++width);
}


