/* 7.1.90 avner ben adapted from iso. */
/* convert text output to mainframe printer - asa code and 7-bit */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

FILE	*inf,*outf;
char	inname[32], outname[32];
char	c;
int	col=0, i;
int	formf=1;
char	asa_code=' ', next_code=' ';
char	ln[81], atln[81];

void putln(void);

int main(int argc,char *argv[])
{
	if (argc==1 || argv[1][0]=='?' || argv[1][1]=='?') {
		puts("PC to Mainframe printfile conversion utility. written by Avner Ben.");
		puts("The input file is searched for the control sequences:");
		puts("home, boldface begin / end, underline begin / end.");
		puts("These are converted to the paralel asa-code solution.");
		puts("Also, all characters above ascii 154 (8-bit) are converted");
		puts("to the paralel \"typewriter graphics\" or spaces.");
		puts("Output file is given the extension .ASA.");
		exit(1);
	} else strcpy(inname,argv[1]);
	for (i=0; inname[i]!='.' && inname[i]!='\0'; ++i)
		outname[i]=inname[i];
	strcpy(&outname[i],".asa");
	puts(outname);
	if ((inf=fopen(inname,"r"))==NULL)
		{ puts("input file not found!"); exit(1); }
	if (!strcmp(inname,outname))
		{ puts("invalid input extension .asa!"); exit(1); }
	if ((outf=fopen(outname,"w"))==NULL)
		{ puts("cannot open output file!"); exit(1); }
	puts("PC to Mainframe printfile conversion utility. written by Avner Ben.");
	while ((c=getc(inf))!=EOF) {
		if (c=='\n') putln();
		else if (c==12) {
			if (col) putln(); formf=1;
		} else if (c=='\033') {
			c=getc(inf);
			if (c=='E') {      /* bold begin */
				asa_code=next_code='b';
			} else if (c=='F')       /* bold end */
				next_code=' ';
			else if (c=='-') {
				c=getc(inf);
				if (c=='1')    /* underline begin */
					asa_code=next_code='u';
				else if (c=='0')  /* undeline end */
					next_code=' ';
			}
		} else if (col<80) {
			if ((unsigned char)c>=155) {
				if (strchr("ÄÍ",c)) c='-';
				else if (strchr("³º",c)) c='|';
				else if (strchr("´µ¶·¸¹»¼½¾¿ÀÁÂÃÅÆÇÈÉÊËÌÎÏÐÑÒÓÔÕÖ×ØÙÚ",c)) c='+';
				else if (strchr("ùú",c)) c='.';
			}
			ln[col]=c;
			if (next_code=='b') atln[col]=c;
			else if (next_code=='u') atln[col]='_';
			else atln[col]=' ';
			col++;
		}
	}
	fclose(inf); fclose(outf);
	return(0);
}

void putln()
{
	int i;
	if (formf) putc('1',outf);
	else putc(' ',outf);
	for (i=0; i<col; i++) putc(ln[i],outf);
	putc('\n',outf);
	if (asa_code!=' ') {
		putc('+',outf);
		for (i=0; i<col; i++) putc(atln[i],outf);
		putc('\n',outf);
	}
	col=formf=0; asa_code=next_code;
}

