/* split.c: split things into n-block hunks */
/* SPLIT filename blockgranularity */
/* splits on a line boundary */
/* revised 8jul85 to do fput() etc not getc() also use ALGOL68*/

#include <stdio.h>
#include <cx.h>
#include <nboff.h>
#include <fdoff.h>
#include <algol68.h>

#define FDBOFF 024
#define NAMESIZE 15
#define BUFSIZ 4096

FILE		*optr;
FILE		*iptr;
char		outname[NAMESIZE+5];
char		name[NAMESIZE];
char		buffer[BUFSIZ];
int		howlong;

op(number)
unsigned	number;
BEGIN
	sprintf(outname,"%s.%d",name,number);
	IF	(!(optr=fopen(outname,"uW")))
	THEN	error("\7Can't make \"%s\"\n",outname);
	FI
END

main(argc,argv)
int		argc;
char		**argv;
BEGIN
unsigned	granularity;
char		*p;
FDB		*fdbp;
unsigned	vbnbreak;	/* break when vbn reaches this */
int		number;		/* counts files created */
	strncpy(name,argv[1],NAMESIZE-1);
	name[NAMESIZE-1]=0;
	IF	(p=strchr(name,'.'))
	THEN	*p=0;	/* no extension */
	FI
	sscanf(argv[2],"%u",&granularity);
	IF	(!(iptr=fopen(argv[1],"ru")))
	THEN	error("\7Can't find \"%s\"\n",argv[1]);
	FI
	fdbp = (char *)(iptr) + FDBOFF;
	vbnbreak = granularity;
	op(number=1);
	WHILE	(!feof(iptr))
	DO	howlong = fget(buffer,BUFSIZ,iptr);
		IF	(ferror(iptr))
		THEN	error("\7$$ferr=%oo fget",$$ferr);
		FI
		IF	(feof(iptr))
		THEN	break;
		FI
		fput(buffer,howlong,optr);
		IF	(ferror(optr))
		THEN	error("\7$$ferr=%oo fput",$$ferr);
		FI
		IF	(fdbp->f_vbn >vbnbreak)
		THEN	IF	(fclose(optr))
			THEN	error("\7Can't close output \"%s\"\n",outname);
			FI
			op(++number);
			vbnbreak += granularity;
		FI
	OD
	IF	(fclose(optr))
	THEN	error("\7Can't close output \"%s\"\n",outname);
	FI
END

/* end: split.c */
