#include stdio
#include rms
#include iodef
#include devdef
#include descrip
#include ssdef
#include ctype

#define STRING "TAPE:"
#define	MAX_BLKSIZE	10240

int chan;		/* Input channel	*/
int	out;		/* Output channel	*/

typedef struct iosb {
	short status;
	short bytcnt;
	int ddinfo;
} IOSB;
IOSB	iosb;

char buffer[MAX_BLKSIZE];

struct dsc$descriptor_s devnam = { 
	sizeof(STRING)-1, DSC$K_DTYPE_T, DSC$K_CLASS_S, STRING };

#define	TRUE	1
#define	FALSE	0
#define	EOS	0

main(argc, argv)
int argc;
char **argv;
{
	register int		status;
	register int		count;

	if (argc < 2) {
	    fprintf(stderr, "You must specify an output file\n\n");
usage:	    fprintf(stderr, "Usage:\t$ ASSIGN magtape_device TAPE\n");
	    fprintf(stderr, "\t$ MOUNT/FOREIGN TAPE:\n");
	    fprintf(stderr, "\treadtape output [r] [skip]\n");
	    fprintf(stderr, "\t\nr\t(optional) rewind magtape\n");
	    fprintf(stderr, "\t\tskip\tnumber of files to skip\n");
	    exit(SS$_ABORT);
	}
	if ((out = creat(argv[1])) == NULL) {
	    fprintf(stderr, "Can't create output file \"%s\"\n\n", argv[1]);
	    goto usage;
	}
	argc--;
	argv++;
	status = sys$assign(&devnam, &chan, 3, 0);
	if (status != SS$_NORMAL)
	    exit(status);
	if (argc > 1 && argv[1][0] == 'r') {
	    argc--;
	    argv++;
	    fprintf(stderr, "Rewinding\n");
	    status = sys$qiow(0, chan, IO$_REWIND, &iosb, 0, 0,
		    0, 0, 0, 0, 0, 0);
	    if (status != SS$_NORMAL || iosb.status != SS$_NORMAL) {
		fprintf(stderr, "IO$_REWIND error: %d %d\n",
			status, iosb.status);
		exit(iosb.status);
	    }
	}
	if (argc > 1 && isdigit(argv[1][0])) {
	    int		skip;

	    skip = atoi(argv[1]);
	    argv++;
	    argc--;
	    fprintf(stderr, "skipping %d file%s\n",
		    skip, (skip != 1) ? "s" : "");
	    status = sys$qiow(0, chan, IO$_SKIPFILE, &iosb, 0, 0,
		    skip, 0, 0, 0, 0, 0);
	    if (status != SS$_NORMAL || iosb.status != SS$_NORMAL) {
		fprintf(stderr, "IO$_SKIPFILE error: %d %d\n",
			status, iosb.status);
		exit(iosb.status);
	    }
	}
	while (argc > 1 && argv[1] != NULL) {
	    fprintf(stderr, "Excess argument \"%s\" ignored\n", argv[1]);
	    argv++;
	    argc--;
	}
	for (count = 0;;) {
	    status = sys$qiow(0, chan, IO$_READVBLK, &iosb,
		    0, 0, buffer, sizeof buffer, 0, 0, 0, 0);
	    if (status != SS$_NORMAL || iosb.status != SS$_NORMAL) {
		printf("status = %d %d, bytcnt = %d, ddinfo = %d\n",
			status, iosb.status, iosb.bytcnt, iosb.ddinfo);
		break;
	    }
	    if (write(out, buffer, iosb.bytcnt) != iosb.bytcnt) {
		fprintf(stderr, "error writing %d bytes\n", iosb.bytcnt);
		break;
	    }
	    ++count;
	    if ((count % 100) == 0)
		fprintf(stderr, "%4d\n", count);
	}
	close(out);
	fprintf(stderr, "Finished after copying %d record%s\n",
		count, (count != 1) ? "s" : "");
	exit (SS$_NORMAL);
}
