/*
 * 5799-WZQ (C) COPYRIGHT IBM CORPORATION 1986,1988
 * LICENSED MATERIALS - PROPERTY OF IBM
 * REFER TO COPYRIGHT INSTRUCTIONS FORM NUMBER G120-2083
 */
/* $Header:copy.c 12.0$ */
/* $ACIS:copy.c 12.0$ */
/* $Source: /ibm/acis/usr/sys/standca/RCS/copy.c,v $ */

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

/*	copy.c	6.1	83/07/29	*/

/*
 * Copy from to in 10K units.
 * Intended for use in system
 * installation.
 */

#define BUFFSIZE 10240		/* 10k units */
#define BLOCKSIZE 512
int from, to, record;

main()
{
	char fbuf[50], tbuf[50];
	register int count;
	extern int errno;

	printf("Standalone copy\n");

	from = getdev("From", fbuf, 0);
	to = getdev("To", tbuf, 1);
	count = getnum("Count (512 byte blocks) ");
	if (count == 0)
		count = 9999999;	       /* a large count */
	else
		{
		int fromoffset = getnum("from block offset ");
		int tooffset;
		if (count < 0)
			count =  getnum("last block ") + 1 - fromoffset;
		tooffset = getnum("to block offset ");
		lseek(from, fromoffset * BLOCKSIZE, 0);
		lseek(to, tooffset * BLOCKSIZE, 0);
		}
	docopy(count);
	printf("Copy completed: %d blocks copied\n", record);
	exit(0);
}



getdev(prompt, buf, mode)
	char *prompt, *buf;
	int mode;
{
	register int i;

	do {
		printf("%s: ", prompt);
		gets(buf);
		i = open(buf, mode);
	} while (i <= 0);
	return (i);
}

getnum(prompt)
	char *prompt;
{
	register int i;
	char buf[80];

	printf("%s: ", prompt);
	gets(buf);
	i = atol(buf);
	return (i);
}

docopy(count)
{
	register int len;
	register int blocks;
	char buffer[BUFFSIZE];

	for (record = 0; record < count; record += blocks) {
		int rcc, wcc;

		blocks = count-record;	/* number of 512 byte records left */
		if (blocks > BUFFSIZE/BLOCKSIZE)
			blocks = BUFFSIZE/BLOCKSIZE;
		len = blocks * BLOCKSIZE;
		rcc = read(from, buffer, len);
		if (rcc == 0)
			break;
		if (rcc < 0) {
			printf("block %d: read error, errno=%d\n",
			    record, errno);
			break;
		}
		if (rcc < len)
			printf("block %d: read short; expected %d, got %d\n",
			    record, sizeof(buffer), rcc);
		/*
		 * For bug in ht driver.
		 */
		if (rcc > len)
			rcc = len;
		wcc = write(to, buffer, rcc);
		if (wcc < 0) {
			printf("block %d: write error: errno=%d\n",
			    record, errno);
			break;
		}
		if (wcc < rcc) {
			printf("block %d: write short; expected %d, got %d\n",
			    record, rcc, wcc);
			break;
		}
	}
}
