
#include <stdlib.h>
#include <stdio.h>
#include "asciibcd.h"
#include "prsf2.h"

#define MAXREC 10000

char fin[300], fon[300];
unsigned char record[MAXREC];

void main(argc, argv)
	int	argc;
	char	**argv;
{
	int optind;
	char *optarg;
	int blank;
        int cons; /* output to console */
	int ftn;
	register int c;
	FILE *fi, *fo;
	int fileflag;
	unsigned char *p;
	int reclen;

	blank = 0;
        cons = 0;
	ftn = 0;
	for (optind = 1, optarg = argv[optind];
		 optind < argc && *optarg == '-' || *optarg == '/';
		 optind++, optarg = argv[optind]) {
		++optarg;
		while (*optarg) {
			switch(*optarg++) {

			case 'b':
				blank = 1;
				break;

                        case 'c':
                                cons = 1;
                                break;

			case 'f':
				ftn = 1;
				break;

			default:
				fprintf(stderr, "Usage: bcd2txt [-fb] <in> <out> <record length>\n");
				fprintf(stderr, "  -b     Translate 0x50 to 0x00 (blank)\n");
				fprintf(stderr, "  -f     Use Fortran character set\n");
				exit(1);
			}
		}
	}

	reclen = MAXREC;
	parsefiles(argc - (optind-1), &argv[optind-1], "bcd", "txt", &reclen);
	if ((fi = fopen(fin, "rb")) == NULL) {
		perror(fin);
		exit(1);
	}
        if ( cons ) fo = stdout;
	else if ((fo = fopen(fon, "w")) == NULL) {
		perror(fon);
		exit(1);
	}
	p = record;
	fileflag = 1;
	while ( (c = fgetc(fi)) != EOF ) {
		if (c & 0200 || p - record == reclen ) { /* || c == 0132) { */
			while (p != record && p[-1] == ' ') {
				p--;
			}
			if (p != record) {
				fwrite(record, 1, p - record, fo);
				fputc('\n', fo);
			} else if (!fileflag) {
				fputc('\n', fo);
			}
			fileflag = 0;
			p = record;
		}
		if (c == 0217) {
			fputc('\f', fo);
			fileflag = 1;
		} else { /* if (c != 0132) { */
			if (blank && (c & 077) == 020) {
				*p++ = ' ';
			} else if (ftn) {
				*p++ = asciialt[c & 077];
			} else {
				*p++ = asciibcd[c & 077];
			}
		}
	}
	if (p != record) {
		while (p != record && p[-1] == ' ') {
			p--;
		}
		if (p != record) {
			fwrite(record, 1, p - record, fo);
			fputc('\n', fo);
		} else if (!fileflag) {
			fputc('\n', fo);
		}
	}
}
