/*
	ps2txt.c						Iqbal Qazi
							      June 6, 1991

	USAGE:  ps2txt [-] | [filename]

	Extracts strings from PostScript file.  Takes input from
	filename or standard input, output goes to standard output.

			i.e.	ps2txt homer.ps
				ps2txt dweezil.ps > dweezil.txt
			 	cat file.ps | ps2txt - | more
				ps2txt - < homer.ps

	   Comments, suggestions, problems to:  Iqbal Qazi
			(iqbal@sparko.gwu.edu)

	VERSION:  1.1	Fixed bug dealing with comments
		  1.2	By popular demand:  put spaces between strings.

*/

#include <stdio.h>
#define ABORT(X,Y) printf(X,Y);puts(usage); exit(0)

char *usage="Usage:  ps2txt [-] | [filename]";
char *str;
char junk[80];
FILE *file, *source;

void main(argc, argv)
int argc; char **argv;
{
	int ch, para=0, last=0;
	str=argv[1];
	if (argc==1) { ABORT("",""); }
	if (argc!=2) { ABORT("ps2txt: Too many arguments.\n\n",""); }
	if ((str[0]=='-') && (str[1]==0))
		source=stdin;
	else if (str[0]!='-')
		if ((file=fopen(argv[1],"r"))==NULL)
			{ABORT("ps2txt: Error opening file:  %s.\n\n",argv[1]);}
		else source=file;
	else
		{ ABORT("ps2txt: No such option:  %s.\n\n",argv[1]); }

	while ((ch=fgetc(source)) != EOF)
	{
	    switch (ch)
	    {
		case '%'  : if (para==0) fgets(junk, 80, source);
				else putchar(ch);
		case '\n' : if (last==1) { puts(""); last=0; } break;
		case '('  : if (para++>0) putchar(ch); break;
		case ')'  : if (para-->1) putchar(ch); 
			        else putchar(' ');
			    last=1; break;

		case '\\' : if (para>0)
			    switch(ch=fgetc(source))
			    {
				case '(' :
				case ')' :  putchar(ch); break;
				case 't' :  putchar('\t'); break;
				case 'n' :  putchar('\n'); break;
				case '\\':  putchar('\\'); break;
				case '0' :  case '1' : case '2' : case '3' :
				case '4' :  case '5' : case '6' : case '7' :
					    putchar('\\');
				default  :  putchar(ch); break;
			    }
			    break;
		default	   :	if (para>0) putchar(ch);
	    }
	}
}
