/* recsiz.c - decus c, rsx
 * takes the bytes of an input file, copies them to an output file
 * with attributes R.FIX FD.CR
 */

#include <stdio.h>
#include <algol68.h>
extern int $$ferr;

helpless()
BEGIN
	fprintf(stderr,"usage RECSIZ infilnam outfilnam recordsize\n");
	fprintf(stderr,"copy bytes from in to out file, ignore input file's\n");
	fprintf(stderr,"attributes, give output file R.FIX FD.CR record length\n");
	fprintf(stderr,"'recordsize'.\n");
	exit();
END


#define IBFSIZ 8192
#define OBFSIZ 8192


int	inf;
int	of;
int	recz;
int	howlong;
char	obuf[OBFSIZ];
char	ibuf[IBFSIZ];
char	*p;
char	*outp;
char	*nd;

main(argc,argv)
int	argc;
char	**argv;
BEGIN
	IF	(argc!=4)
	THEN	helpless();
	FI
	sscanf(argv[3],"%d",&recz);
	IF	(recz<=0)
	THEN	error("\7record size (%d) must exceed 0",recz);
	FI
	IF	(recz>OBFSIZ)
	THEN	error("\7record size may not exceed %d - rebuild me",OBFSIZ);
	FI
	IF	((inf=fopen(argv[1],"urn"))==NULL)
	THEN	error("\7can't find \"%s\"",argv[1]);
	FI
	IF	((of=fopenc(argv[2],recz))==NULL)
	THEN	error("\7can't make \"%s\"",argv[2]);
	FI
	outp = obuf;
	WHILE	(!feof(inf))
	DO	howlong = fget(ibuf,IBFSIZ,inf);
		IF	(ferror(inf))
		THEN	error("\7can't read $$ferr=%oo",$$ferr);
		FI
		IF	(feof(inf))
		THEN	break;
		FI
		nd = ibuf + howlong;
		FOR	(p=ibuf;	p<nd;	p++)
		DO	spit(*p);
		OD
	OD
	spew();
	IF	(fclose(of))
	THEN	error("\7can't close output $$ferr=%oo",$$ferr);
	FI
END

spit(c)
char	c;
BEGIN
	IF	(outp>=obuf+recz)
	THEN	spew();
	FI
	*outp++ = c;
END

spew()
BEGIN
	fput(obuf,outp-obuf,of);
	IF	(ferror(of))
	THEN	error("\7can't write $$ferr=%oo",$$ferr);
	FI
	outp = obuf;
END

/* end recsiz.c */
