/* issortedp.c - display out-of-order records */

/*
 * Subsumes and obsoletes [302,162]issortedp.c .
 * Argv[1] is the input file.
 * Input file is text.
 * Faster, killed bug when line was followed by line with identical text,
 * but extra text on end.
 */

/* ufilter4.c - prototype filter program - line (actually record) oriented */
/*
 * Modular, fast, record filter skeleton.
 * Forces FD.CR on output file.
 * Gets file names from argv[1],[2]. Too hard to use stdin,stdout.
 * The record has NOTHING (like free '\n's) added to it.
 * Howlong = the record size in bytes.
 * Designed for R.VAR files.
 */

#include <stdio.h>
#include <algol68.h>
#include <cx.h>
#include <nboff.h>
#include <fdoff.h>
char *	buffer;		/* where the buffer is				*/
int	bufmax;		/* maximum record size, needed for recinp()	*/
FILE	*inf;		/* input file					*/
FDB *	fdbp;		/* obsolete kludge				*/
int	howlong;	/* char length of this record			*/
char *	last;		/* copy of the previous record			*/
long	recnum;		/* 0-origin record number of buffer[] record	*/

main(argc,argv)
char **argv;
BEGIN
char *	recinp();	/* the record-getter: 0 means end-of-file	*/

	IF	((inf=fopen(argv[1],"urn"))==NULL)
	THEN	error("can't find %s\7",argv[1]);
	FI
	fdbp = inf -> io_fdb;
	IF	(!(buffer=malloc(bufmax=fdbp->f_fatt.f_rsiz+1)))
				/* +1 for EOS at end of string		*/
	THEN	error("max record size=%d.\7",bufmax);
	FI

	IF	(!(last=malloc(bufmax)))
	THEN	error("MAX record size=%d.\7",bufmax);
	FI

	last = "";
	recnum = 0;

	WHILE	(recinp(buffer,bufmax,inf,&howlong))
	DO	buffer[howlong] = EOS;
		IF	(strcmp(buffer,last)<0)
		THEN	printf("%12ld.:\"%s\"\n%12ld.:\"%s\"\n"
				,recnum-1,last,recnum,buffer);
		FI
		copy(last,buffer,howlong+1);
		recnum++;
	OD

END

char * recinp (where,moby,sewer,lenp)	/* 0==end-file, else buf adr	*/
char *	where;				/* buffer			*/
int	moby;				/* buffer size			*/
FILE *	sewer;				/* input file			*/
int *	lenp;				/* return actual record size	*/
BEGIN
	*lenp = fget(where,moby,sewer);
	IF	(ferror(sewer))
	THEN	error("read failure $$ferr=%oo\7\n",$$ferr);
	FI
	return	(feof(sewer)?NULL:where);
END

/* end: ufilter4.c */
/* end: issortedp.c */
