/*  Filter (C) Copyright 1987 by Russell Wallace. This program is in
	the public domain and may be freely distributed. It may not be used
	commercially without the author's permission. If you find this program
	useful,please send a small donation to the author at:
		24 Lower Georges St.
		Dunlaoghaire
		Co. Dublin
		Ireland
	to help finance further software development. Contributions in kind i.e.
	Amiga disks welcome. If you wish to discuss any aspect of the Amiga or
	computers in general,write or phone 807094.

	Usage: Filter [>outputfile] inputfile
	Filter takes the input file and copies it to an output file using only
	valid ASCII characters from the input file. Useful for recovering
	corrupted files, extracting text from object files or converting IFF to
	ASCII.

	If you give copies of this program to anyone,please distribute source
	code with object code to allow examination of programming techniques;
	the Amiga programming environment is so complex that source code is
	very valuable as an information source */

#include <libraries/dos.h>
#include <exec/types.h>

#define MAXBUFFER 256L		/* length of I/O buffers */
#define EOF 257

unsigned char inbuffer[MAXBUFFER],outbuffer[MAXBUFFER];
struct FileInfoBlock *fp;
struct FileInfoBlock *stdout;

unsigned short charin ()			/* input a character */
{
	static short inpoint=MAXBUFFER-1;
	static short maxin  =MAXBUFFER-1;
	LONG Read ();
	if (++inpoint>=maxin)
	{
		maxin=Read (fp,inbuffer,MAXBUFFER);
		inpoint=0;
	}
	if (maxin==0)
		return (EOF);
	return (unsigned short)(inbuffer[inpoint]);
}

charout (ch)				/* output a character */
unsigned short ch;
{
	static long outpoint=-1;
	LONG Write ();
	if ((++outpoint>=MAXBUFFER)||(ch==EOF))
	{
		Write (stdout,outbuffer,outpoint);
		outpoint=0;
	}
	outbuffer[outpoint]=(unsigned char)ch;
}

main (argc,argv)
int argc;		/* number of arguments input by user */
char *argv[];	/* pointers to each argument */
{
	unsigned short ch;
	struct FileInfoBlock *Open ();
	struct FileInfoBlock *Output ();
	stdout=Output ();
	if ((argc<2)||(*argv[1]=='?'))	/* If no arguments or ?,give help */
	{
		Write (stdout,"Usage: Filter [>outputfile] inputfile\n",38L);
		exit (10);
	}
	if ((fp=Open (argv[1],MODE_OLDFILE))==0)	/* Can't open file */
	{
		Write (stdout,"Couldn't open file for filter\n",30L);
		exit (10);
	}
	for (;;)
	{
		ch=charin ();
		if (ch==EOF)
			break;
		if ((ch>31 && ch<127) || ch==10 || ch==9)
			charout (ch);
	}
	charout (EOF);		/* Write out buffered output */
	Close (fp);
}
