/* rsplit.c */
/* prototype filter program - line (actually record) oriented */
#include <stdio.h>
#include <algol68.h>
#include <cx.h>
#include <nboff.h>
#include <fdoff.h>
#define BUFSIZ 4096
char buffer[BUFSIZ];
FILE	*inf;
FILE	*ouf;
extern int $dsw;
extern int $$ferr;
FDB * fdbp;

#define NAMESIZE 42
char name[NAMESIZE];
char outname[NAMESIZE+5];
unsigned	number;
long	maxlines;
long	lines;

char * documentation [] = {
"usage: RSPLIT infilename outfilestem number_of_records",
"infilename is unambiguous file spec of input file",
"outfilestem is dotless prototype file name e.g. STEM",
"number_of_records is the number of records (maximum) per output stem file",
"will copy input to 1 or more output files named STEM.001, STEM.002 ...",
""
};

helpless()
BEGIN
	char *p;
	char **pp;
	FOR	(pp=documentation; *(p=*pp); pp++)
	DO	puts(p);
	OD;
	exit(1);
END

op(num)
unsigned	num;
BEGIN	sprintf(outname,"%s.%03d",name,num);
	IF	(!(ouf=fopen(outname,"wu")))
	THEN	error("\7Can't make file \"%s\"",outname);
	FI;
	fdbp = ouf -> io_fdb;
	fdbp -> f_fatt . f_ratt |= fd_cr;	/* force fd.cr */
END

main(argc,argv)
char **argv;
BEGIN
register int	howlong;	/* char length of this record */
register char * p;

	IF	(argc!=4)
	THEN	helpless();
	FI;
	IF	((inf=fopen(argv[1],"ur"))==NULL)
	THEN	error("can't find %s\7\n",argv[1]);
	FI;
	strncpy(name,argv[2],NAMESIZE-1);
	name[NAMESIZE-1]=0;
	IF	(p=strchr(name,'.'))
	THEN	*p = 0;	/* no '.' allowed */
	FI;
	op(number = 1);
	lines = 0;
	sscanf(argv[3],"%ld",&maxlines);
	WHILE	(!feof(inf))
	DO	howlong = fget(buffer,BUFSIZ,inf);
		IF	(ferror(inf))
		THEN	error("read failure $$ferr=%oo\7\n",$$ferr);
		FI;
		IF	(feof(inf))
		THEN	break;
		FI;
		IF	(++lines > maxlines)
		THEN	lines = 1;
			IF	(fclose(ouf))
			THEN	error("Can't close file \"%s\" $$ferr=%oo",outname,$$ferr);
			FI;
			op(++number);
		FI;
		fput(buffer,howlong,ouf);
		IF	(ferror(ouf))
		THEN	error("write failed $$ferr=%oo\7\n",$$ferr);
		FI;
	OD;
	IF	(fclose(ouf))
	THEN	error("Can't close\n");
	FI;
END
/* end: ufilter.c */

/* end: rsplit.c */
