#include <stdlib.h>
#include <stdio.h>

/*

clean.c  file

Strips the top three bits from a 5-level tape read file, and deletes leading nulls...
... and reverses the bits end to end! Vass dis?! 

Tom Jennings
mru 10 Nov 1998

*/

char gotdata = 0;				/* 1 == found non-null character */
FILE *fi;					/* input file */
FILE *fo;					/* output file */
char fn[256];					/* outptu filename */

void mf(char *, char *, char *);



int
main(argc, argv)
int argc;
char *argv[];
{
int c;

	if (argc < 2) {
		fprintf (stderr, "clean -- strips a raw tape file. 'clean file.raw' Strips the \n");
		fprintf (stderr, "top three bits and deletes leading nulls. Tom Jennings tomj@wps.com\n");
		return(1);
	}
	if ((fi= fopen(argv[1], "rb")) == NULL) {	/* MODE = READ-ONLY, BINARY! */
		printf ("File %s doesn't exist!\n", argv[1]);
		exit(1);
	}
	mf(argv[1],fn,".bdo");				/* make output file file.BDO */
	if ((fo= fopen(fn, "wb")) == NULL) {		/* MODE = WRITE, BINARY */
		fprintf (stderr, "Can't create file %s!\n", fn);
		fclose(fi);
		exit(2);
	}
	while ((c= fgetc(fi)) != EOF) {			/* for each character in the input file, */
		c &= 0x1f;				/* strip upper bits */
		if ((c == '\0') && !gotdata) continue;	/* ignore leading nulls */
		gotdata= 1;
		if (fputc(c, fo) == EOF) {		/* write to output file */
			fprintf (stderr, "ERROR: Write to %s failed! (disk full?)\n", fn);
			fclose(fi); fclose(fo);
			exit(3);
		}
	}
	fclose(fi); fclose(fo);
	return(0);
}

/* Make a filename with specified extention. */

void
mf(in, out, ext)
char *in, *out, *ext;
{
	while (*out= *in++) {				/* copy filename characters */
		if (*out == '.') break;			/* up til the dot, if any */
		++out;
	}
	while (*out++= *ext++);				/* tack on extention */
}


