/* pad.c - right fill lines of text to a width with a byte */
/* If text is too long: pass whole line, so you may still get ragged right */

/* ufilter2.c - prototype filter program - line (actually record) oriented */

	/***************************************\
	*					*
	*	fails for binary files		*
	*					*
	\***************************************/

#include <stdio.h>
#include <algol68.h>
#define BUFSIZ 4096
char buffer[BUFSIZ];

helpless()
BEGIN
	printf("\7usage: %s <infile >outfile recsiz padval {-n}\n","PAD");
	printf("Reads text files, pads records on right to 'recsiz' wide.\n");
	printf("Records that exceed 'recsiz'(decimal) are passed unchanged.\n");
	printf("'padval' is the OCTAL byte value for padding bytes.\n");
	printf("-n means pad left of end-line byte (if present).\n");
	exit();
END

int	howlong;	/* char length of this record */
int	padval;		/* padding char (8 bits actually) */
int	recsiz;		/* pad to this width */
char *	p;		/* scans buffer */
char *	n;		/* marks normal buffer end */
BOOL	nflag;		/* -n */
int	last;		/* last char on input record (may be '\n') */
BOOL	nwork;		/* do -n for this record */

main(argc,argv)
char **argv;
BEGIN
	IF	(argc<3||argc>4)
	THEN	helpless();
	FI
	sscanf(argv[1],"%d",&recsiz);
	IF	(recsiz<=0)
	THEN	fprintf(stderr,"\7recsiz=%d. not allowed",recsiz);
		helpless();
	FI
	n = buffer + recsiz;
	sscanf(argv[2],"%o",&padval);
	IF	(argc>3)
	THEN	IF	(streq(argv[3],"-n"))
		THEN	nflag = TRUE;
		ELSE	fprintf(stderr,"\7bad argv[3]=\"%s\"",argv[3]);
			helpless();
		FI
	ELSE	nflag = FALSE;
	FI
	WHILE	(!feof(stdin))
	DO	howlong = fget(buffer,BUFSIZ,stdin);
		IF	(ferror(stdin))
		THEN	error("read failure $$ferr=%oo\7\n",$$ferr);
		FI
		IF	(feof(stdin))
		THEN	break;
		FI
		last = buffer[howlong-1];
fprintf(stderr,"howlong=%d. last=%oo\n",howlong,last);
		IF	(last!='\n')
		THEN	nwork = FALSE;
		ELSE	nwork = nflag;
		FI
		IF	(howlong<recsiz)
		THEN	FOR	(p=buffer+howlong-(nwork?1:0); p<n; p++)
			DO	*p = padval;
			OD
			IF	(nwork)
			THEN	buffer[recsiz-1] = last;
			FI
		FI

FOR	(p=buffer; p<buffer+15; p++)
DO	printf	("%d.=%oo  ",p-buffer,*p&0xFF);
OD
printf(" recsiz=%d. nwork=%d. nflag=%d.\n",recsiz,nwork,nflag);

		fput(buffer,max(howlong,recsiz),stdout);
		IF	(ferror(stdout))
		THEN	error("write failed $$ferr=%oo\7\n",$$ferr);
		FI
	OD
	exit(IO_SUCCESS);
END
/* end: ufilter2.c */

/* end: pad.c */
