/* nli.c - nifty utility but hard to explain what it does ! */
/* ufilter2.c - prototype filter program - line (actually record) oriented */
#include <stdio.h>
#include <algol68.h>
#define BUFSIZ 4096
char buffer[BUFSIZ];
extern int $$ferr;

int	nin;	/* number of lines in an input group			*/
int	nout;	/* number of lines in an output group			*/
int	ngroup;	/* number of lines in a group				*/
int	linnum;	/* 0-org line number of this line			*/
		/* varies 0 : nout-1					*/
int	rcopy;	/* copy to output lines 0 : rcopy-1			*/
int	rforget;/* forget input lines rcopy : rforget-1			*/

main(argc,argv)
char **argv;
BEGIN
register int	howlong;	/* char length of this record */
	IF	(argc!=3)
	THEN	usage();
	FI;
	sscanf(argv[1],"%d",&nin);
	sscanf(argv[2],"%d",&nout);
	rcopy = min(nin,nout);
	rforget = max(0,nin-nout) + rcopy;
	ngroup = max(nin,nout);
	FOR	(linnum=0;	;	linnum = (++linnum) % ngroup)
	DO	IF	(linnum >= rforget)
		THEN	fput("",0,stdout);
		ELSE	howlong = fget(buffer,BUFSIZ,stdin);
			IF	(feof(stdin))
			THEN	break;
			FI;
			IF	(ferror(stdin))
			THEN	error("read failure $$ferr=%oo\7\n",$$ferr);
			FI;
			IF	(*buffer=='\f')
			THEN	linnum = -1;
			FI;
			/* we have line # linnum in buffer of howlong chars */
			IF	(linnum<rcopy)
			THEN	fput(buffer,howlong,stdout);
				IF	(ferror(stdout))
				THEN	error("write failed $$ferr=%oo\7\n",$$ferr);
				FI;
			FI;
		FI;
	OD;
END
/* end: ufilter2.c */

char	*hints[] =
{
	"usage: NLI <infile >outfile nin nout"
,	"nin:	number of lines in an input group"
,	"nout:	number of lines in an output group"
,	"if nout>nin, then get nout-nin empty lines between groups"
,	"if nin<nout then drop last nin-nout lines of each group"
,	""
};

usage()
BEGIN
char	**pp;
	FOR	(pp=hints;	**pp;	pp++)
	DO	fprintf(stderr,"%s\n",*pp);
	OD;
	exit();
END

/* end: nli.c */
