#define VERSION "2.44"
/*
 *
 * AUTHOR(s)
 *     Mark Senn wrote the early versions of this program for the
 *     BBN BitGraph.  Stephan Bechtolsheim, Bob Brown, Richard
 *     Furuta, James Schaad and Robert Wells improved it.  Norm
 *     Hutchinson ported the program to the Sun.  Neal Holtz ported
 *     it to the Apollo, and from there to producing PostScript
 *     output. Scott Jones added intelligent font substitution.
 *     Piet van Oostrum added support for BSD4.1, the TEXFONTS
 *     environment variable, better positioning, resource (VM) limiting
 *     and PK files.
 *     Les Carr added the capacity for use of LaserWriter builtin fonts
 *     Piet van Oostrum merged the last two changes and rewrote the code for
 *     reading tfm files.
 * This version has been maintained by
 *
 * Piet van Oostrum, Dept of Computer Science, University of Utrecht
 * Padualaan 14, P.O. Box 80.089, 3508 TB Utrecht, The Netherlands
 * Telephone: +31-30-531806. piet@cs.ruu.nl (mcvax!hp4nl!ruuinf!piet)

 */

/* Basic method:
 * Using the local font cacheing machinery that was in the previewer,
 * we can easily manage to send the bitmap for each chracter only once.
 * Two passes are made over each page in the DVI file.  The first pass
 * simply outputs the bitmaps for all characters on that page that haven't
 * been sent before.  The second pass outputs all the character setting
 * and positioning commands.  This allows us to bracket the setting portion
 * with PostScript save's and restore's, thus reclaiming considerable
 * virtual memory after each page.
 *
 * All coordinates are output in the PostScript system (TeX origin),
 * and in integer units of rasters (300/inch) -- except for character
 * widths, which are sent as floating point numbers.
 *
 * About 2 pages of PostScript support code must be sent to the LaserWriter
 * before this stuff goes.  It is automatically included unless the
 * -h option is given.
 */


/* Change log:
 *
 * Early 1985, (nmh) -- ported sun version to Apollo. 
 * A little later (nmh) -- changed to continue on in the event of missing
 *                      font files.
 * 30-Mar-85 (nmh) -- added -a option to specify a different PXL area
 * 30-Mar-85 (nmh) -- changed default PXL area to /pxl118
 * 31-Mar-85 (nmh) -- fixed bug in OpenFontFile() regarding more than MAXOPEN
 *                    PXL files -- changed to mark files as closed in font_entry.
 *  7-Apr-85 (nmh) -- made command line argument decoding case insensitive.
 *                    cleaned up handling of DVI file name argument.
 * 30-May-85 (nmh) -- new version; hacked to output PostScript commands
 *  6-Jun-85 (nmh) -- added relative positioning (20% smaller PostScript output)
 *                    add -m option to specify mag
 * 11-Jun-85 (nmh) -- fixed bug regarding char spacings in very long "words"
 * 12-Jun-85 (nmh) -- v1.02 - process DVI pages in reverse order
 * 13-Jun-85 (nmh) -- fixed bug re PXL files getting opened too often when no PreLoad
 * 14-Jun-85 (nmh) -- font dict created in PostScript only when 1st char of font downloaded
 *                    add -m0 -mh -m1 etc. to specify magsteps
 * 16-Aug-85 (nmh) -- added -c option t0 create output file in spool area (Apollo specific)
 *                    added -h option to copy header file to output
 *                    added -o option to pass options through to PostScript
 * 20-Aug-85 (nmh) -- v1.03
 * 24-Aug-85 (nmh) -- add -q option (for quiet operation).
 *                    changed -o option to check PostScript option
 *                    changed to output coordinates in TeX system (but
 *                    scaled to raster units) -- (0,0) at 1" in and down from
 *                      top left (better for use with different size paper).
 *                 -- v2.00
 * 25-Aug-85 (nmh) -- added dictionary enclosure to Tex.ps, and output
 *                      suitable prolog here.
 * 26-Aug-85 (nmh) -- changes to tex.ps to support Macintosh documents.
 * 14-Sep-85 (nmh) -- added keyword=value decoding to \special;
 * 15-Sep-85 (nmh) -- added -i file option.
 * 23-Sep-85 (saj) -- added font substitution for case when font is
 *                    unavailable at requested mag. (a frequent occurrence
 *                    with some macro packages like LaTeX)
 * 29-May-86 (pvo) -- modified to read PK files rather than pxl files
 * 02-Jun-86 (pvo) -- modified to limit VM usage for big characters
 * 10-Jul-86 (pvo) -- modified area handling to include TEXFONTS path
 * 10-Jul-86 (pvo) -- modified positioning to use Knuth's algorithm
				 (more or less)
 * 11-May-87 (pvo) -- general cleanup
 * 13-Mar-87 (lac) -- added -x option for Soton user
 * ??-Mar-87 (lac) -- added pstext \special keyword
 * 18-Mar-87 (lac) -- new version which uses built-in fonts on the Apple
 *		      LaserWriter and allows the use of psfig
 * 12-May-87 (pvo) -- merges (lac) and (pvo) changes
 * 14-May-87 (pvo) -- rewrote tfm file reading
 * 27-May-87 (pvo) -- changed SetString to check for rounding errors
 * 05-Jun-87 (pvo) -- include path search for fontmap and tfm files
 * 06-Nov-87 (pvo) -- enhanced the x option to include ranges.
 * 30-Mar-89 (pvo) -- applied a patch from Mario Wolczko in main
 *                    (case FNT*)
 * 04-Apr-89 (pvo) -- introduced compile time parameter PAPERSIZE
 * 05-Apr-89 (pvo) -- introduced option -P instead of -x (this change was
 *                    lost somewhere)
 * 27-Apr-89 (pvo) -- introduced options -E/-O for even/odd page selection
 */


/**********************************************************************/
/***********************  external definitions  ***********************/
/**********************************************************************/

#include <sys/param.h>
#include <signal.h>
#include <stdio.h>
#include <ctype.h>
#include "commands.h"
#include "dvi2ps.h"
#include "findfile.h"
#include "postscript.h"
#include "pxlfile.h"

/**********************************************************************/
/*************************  External Procedures  **********************/
/**********************************************************************/

int     ChkOpt();               /* Check PostScript option for validity */
void    DoSpecial();
int     HasBeenRead();
void	Init_Page();
void	MoveDown();
void	MoveOver();
#ifdef STATS
void	Print_Stats();
#endif STATS
int	ReadFontDef();
void	SetChar();
void	SetFntNum();
void	SetRule();
void    SetString();
int	SplitPath();
#ifdef BUILTIN
void	ReadMap();
#endif


/**********************************************************************/
/*************************  Global Procedures  ************************/
/**********************************************************************/

/* Note: Global procedures are declared here in alphabetical order, with
   those which do not return values typed "void".  Their bodies occur in
   alphabetical order following the main() procedure.  The names are
   kept unique in the first 6 characters for portability. */

void	AbortRun();
float	ActualFactor();
void	AllDone();
FILE*	BINARYOPEN();
void    CopyFile();
void    DecodeArgs();
void	Fatal();
int	FindPath();
void	FindPostAmblePtr();
void	GetBytes();
void	GetFontDef();
int	InPageList();
int     IsSame();
void    lcase();
int     NoSignExtend();         /* see cautionary note in code, re arithmetic vs logical shifts */
#ifdef CREOPT
FILE*   OpenOutput();
#endif CREOPT
void	ReadPostAmble();
int     SignExtend();           /* see cautionary note in code, re arithmetic vs logical shifts */
void	SkipFontDef();
int	SplitPath();
void	Warning();


/**********************************************************************/
/*************************  Global Variables  *************************/
/**********************************************************************/

#ifdef DEBUG
int Debug = 0;
#endif
int   FirstPage = -1000000;     /* first page to print (uses count0)   */
int   LastPage = 1000000;       /* last page to print                    */
/* select even/odd pages */
enum  {EO_ALL, EO_EVEN, EO_ODD} EvenOdd = EO_ALL;

/* We need to remember which pages the user would like.  We build a linked
   list that allows us to decide (for any given page) whether it should
   be included in the output file.
*/
struct pagelist {
    struct pagelist *pl_alt;	/* next in a series of alternates */
	int ps_low, ps_high;	/* allowed range */
} *PageList = 0;	/* the list of allowed pages */

char filename[STRSIZE];         /* DVI file name			   */

int   G_create = FALSE;         /* create an output file in spool area ?   */
int   G_errenc = FALSE;	        /* has an error been encountered?          */
int   G_header = TRUE;          /* copy header file to output?             */
char  G_Logname[STRSIZE];       /* name of log file, if created            */
int   G_interactive = FALSE;    /* is the program running interactively    */
                                /* (i.e., standard output not redirected)? */
int   G_logging = 0;            /* Are we logging warning messages?        */
int   G_logfile = FALSE;        /* Are these messages going to a log file? */
FILE *G_logfp;                  /* log file pointer (for errors)           */
char  G_progname[STRSIZE];      /* program name                            */
int   G_quiet = FALSE;          /* for quiet operation                     */
int   G_nowarn = FALSE;         /* don't print out warnings                */
char *Ifile[100];               /* files to include */
int   ncopies = 1;              /* number of copies to print                */
int   ndone = 0;                /* number of pages converted */
int   nif = 0;                  /* number of files to include */
int   nps = 0;                  /* number of PostScript commands to send    */
#ifdef CREOPT
char  outfname[256];            /* name of output file                      */
#endif CREOPT
long  postambleptr;		/* Pointer to the postamble                 */
long  ppagep;	                /* previous page pointer		     */
char *PScmd[100];               /* PostScript commands to send              */
#ifdef BUILTIN
int   PShdr;			/* is PS header to be sent */
#endif
int   Reverse = TRUE;         /* process DVI pages in reverse order ? */
char  rootname[STRSIZE];      /* DVI filename without extension */

#ifdef STATS
int   Stats = FALSE;          /* are we reporting stats ?                 */
int   Snbpxl = 0;             /* # of bytes of pixel data                 */
int   Sonbpx = 0;             /* "optimal" number of bytes of pixel data  */
int   Sndc = 0;               /* # of different characters typeset        */
int   Stnc = 0;               /* total # of chars typeset                 */
int   Snbpx0, Sndc0, Stnc0;   /* used for printing incremental changes per dvi page */
#endif

int	num, den;		/* num/den from dvi file                    */
int	mag;			/* magnification specified in preamble      */
FILE	*outfp = NULL;          /* output file                              */
int	usermag = 0;            /* user specified magnification */
FILE	*dvifp  = NULL;		/* DVI file pointer                         */
int	PreLoad = TRUE;	        /* preload the font descriptions?	     */
extern int h, hh, v, vv;

/**********************************************************************/
/*******************************  main  *******************************/
/**********************************************************************/

main(argc, argv)
int argc;
char *argv[];

{
    struct stack_entry {  /* stack entry */
	int h, v, w, x, y, z, hh, vv;  /* what's on stack */
    };


    int command;	    /* current command			     */
    int count[10];          /* the 10 counters at begining of each page */
    long cpagep;	    /* current page pointer		     */
    int  Emitting = FALSE;  /* are we outputting typsetting instructions? */
    register int i;	    /* command parameter; loop index	     */
    int k;		    /* temporary parameter		     */
    char n[STRSIZE];	    /* command parameter		     */
    int PassNo = 0;         /* which pass over the DVI page are we on?  */
    int SkipMode = FALSE;   /* in skip mode flag                     */
    int sp;		    /* stack pointer			     */
    struct stack_entry stack[STACKSIZE];   /* stack		     */
    int t;		    /* temporary			     */
    char SpecialStr[STRSIZE]; /* "\special" strings                  */
    register struct char_entry *tcharptr; /* temporary char_entry ptr*/
    int val, val2;          /* temporarys to hold command information*/
    int w;		    /* current horizontal spacing	     */
    int x;		    /* current horizontal spacing	     */
    int y;		    /* current vertical spacing		     */
    int z;		    /* current vertical spacing		     */

    strcpy(G_progname, argv[0]);

    *PXLpath = getenv ("TEXFONTS");
    if (! *PXLpath || ! **PXLpath) {
      *PXLpath = PXLAREA;       /* default pixel area */
      *TFMpath = FONTAREA;      /* default font area */
    }
    else *TFMpath = *PXLpath;

    DecodeArgs( argc, argv );
#ifdef BUILTIN
    ReadMap();
#endif

#ifdef apollo
    set_sbrk_size( 2048*1024 );
#endif

    if ((i = NoSignExtend(dvifp, 1)) != PRE)  {
	fprintf(stderr,"\n");
	Fatal("PRE doesn't occur first--are you sure this is a DVI file?\n\n");
    }

    i = SignExtend(dvifp, 1);
    if (i != DVIFORMAT)  {
	fprintf(stderr,"\n");
	Fatal("DVI format = %d, can only process DVI format %d files\n\n",
	 i, DVIFORMAT);
    }

#ifdef CREOPT
    if( G_create )
        outfp = OpenOutput();
    else
#endif CREOPT
        outfp = stdout;

/* it is important that these be the very first things output !!! */

    if( G_header )
        CopyFile( HDRFILE );

    for( i=0; i<nif; i++ )      /* copy all included files */
        CopyFile( Ifile[i] );

#ifdef BUILTIN
    PShdr = G_header;
#endif

#ifndef PAPERSIZE
#define PAPERSIZE "@a4\n"
#endif

    EMIT(outfp, "TeXDict begin @start\n");
    EMIT(outfp, "%%%%Title: %s\n", filename);
    EMIT(outfp, "%%%%Creator: %s %s\n", G_progname, VERSION);
    EMIT(outfp, "%%%%EndProlog\n");
    EMIT(outfp, PAPERSIZE);

    for( i=0; i<nps; i++ )      /* prefix valid PostScript options with a "@" */
        if( ChkOpt(PScmd[i]) )
            EMIT(outfp, "@%s\n", PScmd[i]);
        else
            Fatal( "%s is an invalid option\n", PScmd[i] );

    if( ncopies > 1 )
        EMIT(outfp, "%d @copies\n", ncopies);

    if (Reverse) {
        ReadPostAmble(PreLoad);
        fseek(dvifp, ppagep, 0);
        }
    else {
        if (PreLoad) {
            ReadPostAmble(TRUE);
            fseek(dvifp, (long) 14, 0);
            }
        else {
    	    num = NoSignExtend(dvifp, 4);
    	    den = NoSignExtend(dvifp, 4);
    	    mag = NoSignExtend(dvifp, 4);
#ifdef USEGLOBALMAG
            if( usermag > 0 && usermag != mag )
                fprintf(stderr, "DVI magnification of %d over-ridden by user mag of %d\n", mag, usermag );
#endif
            if( usermag > 0 ) mag = usermag;
#ifndef USEGLOBALMAG
            if( mag != 1000 ) fprintf(stderr, "Magnification of %d ignored.\n", mag);
#endif
    	    hconv = DoConv(num, den, hconvRESOLUTION);
    	    vconv = DoConv(num, den, vconvRESOLUTION);
            }
        k = NoSignExtend(dvifp, 1);
        GetBytes(dvifp, n, k);
        }

    PassNo = 0;
    
    while (TRUE)

	switch (command=NoSignExtend(dvifp, 1))  {

	case SET1:case SET2:case SET3:case SET4:
	    val = NoSignExtend(dvifp, command-SET1+1);
	    if (!SkipMode) SetChar(val, command, PassNo);
	    break;

	case SET_RULE:
	    val = NoSignExtend(dvifp, 4);
	    val2 = NoSignExtend(dvifp, 4);
            if (Emitting) SetRule(val, val2, 1);
	    break;

	case PUT1:case PUT2:case PUT3:case PUT4:
	    val = NoSignExtend(dvifp,command-PUT1+1);
	    if (!SkipMode) SetChar(val, command, PassNo);
	    break;

	case PUT_RULE:
	    val = NoSignExtend(dvifp, 4);
	    val2 = NoSignExtend(dvifp, 4);
            if (Emitting) SetRule(val, val2, 0);
	    break;

	case NOP:
	    break;

	case BOP:
	    cpagep = ftell(dvifp) - 1;
	    for (i=0; i<=9; i++)
		count[i] = NoSignExtend(dvifp, 4);
	    ppagep = NoSignExtend(dvifp, 4);
	    sp = 0;
	    Init_Page();
	    w = x = y = z = 0;
	    if(InPageList(count[0]))
		SkipMode= FALSE;
            else if( count[0] < FirstPage || count[0] > LastPage) 
                	SkipMode = TRUE;
	    else
                	SkipMode = FALSE;
	    if ( EvenOdd == EO_EVEN && count[0]%2 ||
		 EvenOdd == EO_ODD && !(count[0]%2) )
		SkipMode = TRUE;

            Emitting = (PassNo != 0) && !SkipMode;

            if( !SkipMode ) {
                if( PassNo == 0) {
                        EMIT(outfp,"%d @bop0\n", count[0]);
#ifdef STATS
                        if( Stats ) {
                                Sndc0 = Sndc;
                                Stnc0 = Stnc;
                                Snbpx0 = Snbpxl;
                                }
#endif
                        if( !G_quiet ) 
                                fprintf(stderr, "[%d", count[0] );
                        }
                else
                        EMIT(outfp,"%d @bop1\n", count[0]);
                }
	    break;

	case EOP:
            if( !SkipMode ) {
                if( PassNo == 0 ) {     /* start second pass on current page */
                    fseek(dvifp,cpagep,0);
                    PassNo = 1;
                    }
                else {                  /* end of second pass, and of page processing */
                    EMIT(outfp,"@eop\n");
#ifdef STATS
                    if( Stats )
                        fprintf(stderr," - %d total ch,  %d diff ch,  %d pxl bytes]\n",
                                Stnc-Stnc0, Sndc-Sndc0, Snbpxl-Snbpx0);   
                    else
#endif
                        if( !G_quiet ) {
                                fprintf(stderr,"] ");
                                if( (++ndone % 10) == 0 ) fprintf(stderr,"\n");
                                }
                    PassNo = 0;
                    }
                }
            else
                PassNo = 0;
            if( PassNo == 0 && Reverse ) { 
                if( ppagep > 0 )
                    fseek(dvifp, ppagep, 0);
                else 
                    AllDone();
                }
	    break;

	case PUSH:
	    if (sp >= STACKSIZE)
		Fatal("stack overflow");
	    stack[sp].h = h;
	    stack[sp].v = v;
	    stack[sp].w = w;
	    stack[sp].x = x;
	    stack[sp].y = y;
	    stack[sp].z = z;
	    stack[sp].hh = hh;
	    stack[sp].vv = vv;
	    sp++;
	    break;

	case POP:
	    --sp;
	    if (sp < 0)
		Fatal("stack underflow");
	    hh = stack[sp].hh;
	    vv = stack[sp].vv;
	    h = stack[sp].h;
	    v = stack[sp].v;
	    w = stack[sp].w;
	    x = stack[sp].x;
	    y = stack[sp].y;
	    z = stack[sp].z;
	    break;

	case RIGHT1:case RIGHT2:case RIGHT3:case RIGHT4:
            val = SignExtend(dvifp,command-RIGHT1+1);
	    if (Emitting) MoveOver(val);
	    break;

	case W0:
            if (Emitting) MoveOver(w);
	    break;

	case W1:case W2:case W3:case W4:
	    w = SignExtend(dvifp,command-W1+1);
            if (Emitting) MoveOver(w);
	    break;

	case X0:
            if (Emitting) MoveOver(x);
	    break;

	case X1:case X2:case X3:case X4:
	    x = SignExtend(dvifp,command-X1+1);
	    if (Emitting) MoveOver(x);
	    break;

	case DOWN1:case DOWN2:case DOWN3:case DOWN4:
            val = SignExtend(dvifp,command-DOWN1+1);
	    if (Emitting) MoveDown(val);
	    break;

	case Y0:
            if (Emitting) MoveDown(y);
	    break;

	case Y1:case Y2:case Y3:case Y4:
	    y = SignExtend(dvifp,command-Y1+1);
            if (Emitting) MoveDown(y);
	    break;

	case Z0:
            if (Emitting) MoveDown(z);
	    break;

	case Z1:case Z2:case Z3:case Z4:
	    z = SignExtend(dvifp,command-Z1+1);
	    if (Emitting) MoveDown(z);
	    break;

	case FNT1:case FNT2:case FNT3:case FNT4:
	    k = NoSignExtend(dvifp,command-FNT1+1);
            if (!SkipMode) {
		SetFntNum(k, Emitting);
	    }
	    break;

	case XXX1:case XXX2:case XXX3:case XXX4:
	    k = NoSignExtend(dvifp,command-XXX1+1);
            GetBytes(dvifp, SpecialStr, k);
            if(Emitting) DoSpecial(SpecialStr, k);
	    break;

	case FNT_DEF1:case FNT_DEF2:case FNT_DEF3:case FNT_DEF4:
            k = NoSignExtend(dvifp, command-FNT_DEF1+1);
	    if (PreLoad || HasBeenRead(k) )
	    {
		SkipFontDef (k);
	    }
	    else
	    {
		ReadFontDef (k);
	    }
	    break;

	case PRE:
	    Fatal("PRE occurs within file");
	    break;

	case POST:
            AllDone();
	    break;

	case POST_POST:
 	    Fatal("POST_POST with no preceding POST");
	    break;

	default:
	    if (command >= FONT_00 && command <= FONT_63)
		{if (!SkipMode)
                     SetFntNum(command - FONT_00, Emitting);}
	    else if (command >= SETC_000 && command <= SETC_127)
		{if (!SkipMode) SetString(command, PassNo);}
	    else
		Fatal("%d is an undefined command", command);
	    break;

	}

}

/*-->AbortRun*/
/**********************************************************************/
/***************************  AbortRun  *******************************/
/**********************************************************************/

void
AbortRun(code)
int code;
{
    exit(code);
}


/*-->ActualFactor*/
/**********************************************************************/
/**************************  ActualFactor  ****************************/
/**********************************************************************/

float		/* compute the actual size factor given the approximation */
ActualFactor(unmodsize)
int unmodsize;  /* actually factor * 1000 */
{
    float realsize;	/* the actual magnification factor */

    realsize = (float)unmodsize / 1000.0;
    /* a real hack to correct for rounding in some cases--rkf */
    if(unmodsize==1095) realsize = 1.095445;	/*stephalf*/
    else if(unmodsize==1315) realsize=1.314534;	/*stepihalf*/
    else if(unmodsize==1577) realsize=1.577441;	/*stepiihalf*/
    else if(unmodsize==1893) realsize=1.892929;	/*stepiiihalf*/
    else if(unmodsize==2074) realsize=2.0736;	/*stepiv*/
    else if(unmodsize==2488) realsize=2.48832;  /*stepv*/
    else if(unmodsize==2986) realsize=2.985984;	/*stepiv*/
    /* the remaining magnification steps are represented with sufficient
	   accuracy already */
    return(realsize);
}


/*-->AllDone*/
/**********************************************************************/
/****************************** AllDone  ******************************/
/**********************************************************************/

void
AllDone()
{
    char t;
    struct font_entry *p;
    int per;

    EMIT(outfp,"@end\n");
    if( !G_quiet ) fprintf(stderr,"\n");

#ifdef CREOPT
    if( G_create ) {
        fclose(outfp);
        if( !G_quiet ) fprintf(stderr, "Output written on \"%s\"\n", outfname );
        }
#endif CREOPT

    if (G_errenc && G_logging == 1 && G_logfile)  {
	fseek(G_logfp, 0, 0);
	while ((t=getc(G_logfp)) != EOF)
	    putchar(t);
    }
    if (G_logging == 1 && G_logfile) printf("Log file created\n");

#ifdef STATS
    if (Stats) Print_Stats;
#endif

    AbortRun(G_errenc);
}


/*-->CopyFile*/   /* copy a file straight through to output */
/*********************************************************************/
/***************************** CopyFile ******************************/
/*********************************************************************/

void
CopyFile( str )
char    *str;
{
        FILE    *spfp;
        char    t;

        if( (spfp=fopen(str,"r")) == NULL ) {
                fprintf(stderr,"Unable to open file %s\n", str );
                return;
                }
        if( !G_quiet ) fprintf(stderr," [%s", str);
        while( (t = getc(spfp)) != EOF ) {
                if (t >= '\010') EMITC(t); /* Don't transmit controls */
                }              
        fclose(spfp);
        if( !G_quiet ) fprintf(stderr,"]");
}


/*-->DecodeArgs*/
/*********************************************************************/
/***************************** DecodeArgs ****************************/
/*********************************************************************/

void
DecodeArgs( argc, argv )
int argc;
char *argv[];
{
    int argind;             /* argument index for flags              */
    char curarea[STRSIZE];  /* current file area		     */
    char curname[STRSIZE];  /* current file name		     */
    char *tcp, *tcp1;	    /* temporary character pointers	     */

    argind = 1;
    while (argind < argc) {
	tcp = argv[argind];
        if (*tcp == '-')
	    /* switch(isupper(*++tcp) ? (*tcp-'A')+'a' : *tcp) {*/
            switch (*++tcp) {

                case 'a':       /* a selects different pxl font area */
                    *PXLpath = *TFMpath = argv[++argind];
                    break;
#ifdef CREOPT
                case 'c':       /* create an output file in spool area */
                    G_create = TRUE;
                    break;
#endif CREOPT
#ifdef DEBUG
		case 'd':	/* d selects Debug output */
		    Debug = TRUE;
		    break;
#endif
                case 'f':       /* next arg is starting pagenumber */
                    if( ++argind >= argc || sscanf(argv[argind], "%d", &FirstPage) != 1 )
                        Fatal("Argument is not a valid integer\n", 0);
                    break;

                case 'h':       /* don't copy PostScript header file through to output */
                    G_header = FALSE;
                    break;

                case 'i':       /* next arg is a PostScript file to copy */
                    if( ++argind >= argc )
                        Fatal("No argument following -i\n", 0);
                    Ifile[nif++] = argv[argind];
                    break;

		case 'l':	/* l prohibits logging of errors */
		    G_logging = -1;
		    break;
#ifdef USEGLOBALMAG
                case 'm':       /* specify magnification to use */
                    switch( (isupper(*++tcp)? tolower(*tcp): *tcp)) {

                    case '\0':       /* next arg is a magnification to use */
                        if( ++argind >= argc || sscanf(argv[argind], "%d", &usermag) != 1 )
                            Fatal("Argument is not a valid integer\n", 0);
                        break; 
                    case '0': usermag = 1000; break;
                    case 'h': usermag = 1095; break;
                    case '1': usermag = 1200; break;
                    case '2': usermag = 1440; break;
                    case '3': usermag = 1728; break;
                    case '4': usermag = 2074; break;
                    case '5': usermag = 2488; break;
                    default: Fatal("%c is a bad mag step\n", *tcp);
                    }
                    break;
#endif
                case 'n':       /* next arg is number of copies to print */
                    if( ++argind >= argc || sscanf(argv[argind], "%d", &ncopies) != 1 )
                        Fatal("Argument is not a valid integer\n", 0);
                    break;    

                case 'o':       /* next arg is a PostScript command to send */
                    if( ++argind >= argc )
                        Fatal("No argument following -o\n", 0);
                    PScmd[nps++] = argv[argind];
                    break;

		case 'p':	/* p prohibits pre-font loading */
		    PreLoad = 0;
                    Reverse = FALSE;    /* must then process in forward order */
		    break;

                case 'q':       /* quiet operation */
                    G_quiet = TRUE;
                    break;

                case 'r':       /* don't process pages in reverse order */
                    Reverse = FALSE;
                    break;
#ifdef STATS                   
                case 's':       /* print some statistics */
                    Stats = TRUE;
                    break;
#endif
                case 't':       /* next arg is ending pagenumber */
                    if( ++argind >= argc || sscanf(argv[argind], "%d", &LastPage) != 1 )
                        Fatal("Argument is not a valid integer\n", 0);
                    break;

                case 'w':       /* don't print out warnings */
                    G_nowarn = TRUE;
                    break;

		case 'x':	/* next argument is a list of page numbers
				   for printing */
		case 'P':
		    if( ++argind >=argc || ParsePages(argv[argind] ))
			Fatal("Argument is not a valid pagelist\n", 0);
		    break;

		case 'E':	/* print only even pages */
		    EvenOdd = EO_EVEN;
		    break;

		case 'O':	/* print only odd pages */
		    EvenOdd = EO_ODD;
		    break;

		default:
		    printf("%c is not a legal flag\n", *tcp);
		}

        else {

            tcp = rindex(argv[argind], '/');    /* split into directory + file name */
            if (tcp == NULL)  {
        	curarea[0] = '\0';
        	tcp = argv[argind];
                }
            else  {
        	strcpy(curarea, argv[argind]);
                curarea[tcp-argv[argind]+1] = '\0';
        	tcp ++;
                }
        
            strcpy(curname, tcp);
            tcp1 = rindex(tcp, '.');   /* split into file name + extension */
            if (tcp1 == NULL) {
                strcpy(rootname, curname);
                strcat(curname, ".dvi");
                }
            else {
                *tcp1 = '\0';
                strcpy(rootname, curname);
                *tcp1 = '.';
                }
        
            strcpy(filename, curarea);
            strcat(filename, curname);
        
            if ((dvifp=BINARYOPEN(filename,"r")) == NULL)  {
        	fprintf(stderr,"\n");
        	fprintf(stderr,"%s: can't find DVI file \"%s\"\n\n", G_progname, filename);
        	AbortRun(1);
                }
        
            strcpy(G_Logname, curname);
            strcat(G_Logname, ".log");
	    }
	argind++;
        }

    if (dvifp == NULL)  {
	fprintf(stderr, 
                "\nusage: %s [-a area] [-c] [-h] [-o option] [-p] [-s] [-r] [-f n] [-t n] [-m{0|h|1|2|3|4|  mag] [-a fontarea] dvifile\n\n", 
                G_progname);
	AbortRun(1);
        }
    PXLpathlen = SplitPath(PXLpath);
    TFMpathlen = SplitPath(TFMpath);
}

/*-->DoConv*/
/*********************************************************************/
/********************************  DoConv  ***************************/
/*********************************************************************/

int DoConv(num, den, convResolution)
{
    register float conv;
    conv = ((float)num/(float)den) * 
#ifdef USEGLOBALMAG
/*	ActualFactor(mag) * why was this in as Actual Factor?  jls */
	((float) mag/1000.0) *
#endif
	((float)convResolution/254000.0);
    return((int) (1.0 / conv + 0.5));
}

/*-->Fatal*/
/**********************************************************************/
/******************************  Fatal  *******************************/
/**********************************************************************/

void
Fatal(fmt, a, b, c)/* issue a fatal error message */
char *fmt;	/* format */
char *a, *b, *c;	/* arguments */

{
    if (G_logging == 1 && G_logfile)
    {
	fprintf(G_logfp, "%s: FATAL--", G_progname);
	fprintf(G_logfp, fmt, a, b, c);
	fprintf(G_logfp, "\n");
    }

    fprintf(stderr,"\n");
    fprintf(stderr, "%s: FATAL--", G_progname);
    fprintf(stderr, fmt, a, b, c);
    fprintf(stderr, "\n\n");
    if (G_logging == 1) printf("Log file created\n");
#ifdef CREOPT
    if (G_create && outfp != NULL) {
        fclose(outfp);
        unlink(outfname);
        }
#endif CREOPT
    AbortRun(1);
}


/*-->FindPath*/
/**********************************************************************/
/****************************  FindPath  ******************************/
/**********************************************************************/

int
FindPath (path, len, file, out)
char **path, *file, *out;
int len;
{
	int i;
	char fn[STRSIZE];
	for (i=0; i<len; i++) {
	  sprintf (fn, "%s/%s", path[i], file);
	  if (! access (fn, 4)) {
	    strcpy( out, fn );
	    return i;
	  }
	}
	return -1;
}


/*-->FindPostAmblePtr*/
/**********************************************************************/
/************************  FindPostAmblePtr  **************************/
/**********************************************************************/

void
FindPostAmblePtr(postambleptr)
long	*postambleptr;

/* this routine will move to the end of the file and find the start
    of the postamble */

{
    int     i;

    fseek (dvifp, (long) 0, 2);   /* goto end of file */
    *postambleptr = ftell (dvifp) - 4;
    fseek (dvifp, *postambleptr, 0);

    while (TRUE) {
	fseek (dvifp, --(*postambleptr), 0);
	if (((i = NoSignExtend(dvifp, 1)) != 223) &&
	    (i != DVIFORMAT))
	    Fatal ("Bad end of DVI file");
	if (i == DVIFORMAT)
	    break;
    }
    fseek (dvifp, (*postambleptr) - 4, 0);
    (*postambleptr) = NoSignExtend(dvifp, 4);
    fseek (dvifp, *postambleptr, 0);
}


/*-->GetBytes*/
/**********************************************************************/
/*****************************  GetBytes  *****************************/
/**********************************************************************/

void
GetBytes(fp, cp, n)	/* get n bytes from file fp */
register FILE *fp;	/* file pointer	 */
register char *cp;	/* character pointer */
register int n;		/* number of bytes  */

{
    while (n--)
	*cp++ = getc(fp);
}


/*-->GetFontDef*/
/**********************************************************************/
/**************************** GetFontDef  *****************************/
/**********************************************************************/

void
GetFontDef()

/***********************************************************************
   Read the font  definitions as they  are in the  postamble of the  DVI
   file.
***********************************************************************/

{
    char    str[50], *calloc ();
    unsigned char   byte;
    int     i, fnamelen;

    while (((byte = NoSignExtend(dvifp, 1)) >= FNT_DEF1) &&
	(byte <= FNT_DEF4))
	    ReadFontDef (NoSignExtend(dvifp, byte-FNT_DEF1+1));
    if (byte != POST_POST)
	Fatal ("POST_POST missing after fontdefs");
}



/*-->InPageList*/
/**********************************************************************/
/******************************  InPageList  **************************/
/**********************************************************************/
/* Return true iff i is one of the desired output pages */

int InPageList(i)
int i;{
    register struct pagelist   *pl = PageList;

    while (pl) {
	    if ( i >= pl -> ps_low && i <= pl -> ps_high)
		return 1;		/* success */
	pl = pl -> pl_alt;
    }
    return 0;
}


/*-->IsSame*/
/**********************************************************************/
/*******************************  IsSame  *****************************/
/**********************************************************************/

int IsSame(a, b)        /* compare strings, ignore case */
char *a, *b;
{
        for( ; *a != '\0'; )
                if( tolower(*a++) != tolower(*b++) ) return( FALSE );
        return( *a == *b ? TRUE : FALSE );
}


/*-->lcase*/
/**********************************************************************/
/****************************  lcase  *********************************/
/**********************************************************************/

void lcase(s)
char *s;
{
        char *t;
        for(t=s; *t != '\0'; t++)
	  *t = tolower(*t);
        return;
}


/*-->NoSignExtend*/
/**********************************************************************/
/***************************  NoSignExtend  ***************************/
/**********************************************************************/

int
NoSignExtend(fp, n)	/* return n byte quantity from file fd */
register FILE *fp;	/* file pointer    */
register int n;		/* number of bytes */

{
    register int x;	/* number being constructed */

    x = 0;
    while (n--)  {
	x <<= 8;
	x |= getc(fp);
    }
    return(x);
}

#ifdef CREOPT
/*-->OpenOutput*/   /* generate a unique file name and open it */
/**********************************************************************/
/*************************** OpenOutput *******************************/
/**********************************************************************/


FILE*
OpenOutput()
{
        FILE*   fp;
        long t;
        int  n = 0;
        char *p, *pp, b[256];
        int nd;

        time( &t );
        t = t % 100000;
        strcpy( outfname, SPOOLFILE );
        sprintf( b, "%s.%s.%x", logname(), rootname, t );
        if( (nd=strlen(b)-MAXFLEN) > 0 ) {
               for(pp=(p=rindex(b,'.')); p && *p != '\0'; *(pp-nd) = *p++, pp++) ;
               *(pp-nd) = '\0';
               }
        strcat( outfname, b );

        while( access(outfname,0) == 0 ) {
                n ++;
                if( n > 10 ) 
                        Fatal( "Unable to create a unique output file name: %s\n", outfname );
                strcpy( outfname, SPOOLFILE );
                sprintf( b, "%s.%s.%x.%d", logname(), rootname, t, n );
                if( (nd=strlen(b)-MAXFLEN) > 0 ) {
                        for(pp=(p=rindex(b,'.')); p && *p != '\0'; *(pp-nd) = *p++, pp++) ;
                        *(pp-nd) = '\0';
                        }
                strcat( outfname, b );
                }

        if( (fp=fopen(outfname,"w")) == NULL )
                Fatal("Unable to create output file: %s\n", outfname);

        return( fp );
}
#endif CREOPT

struct pagelist *
InstallPL (pslow, pshigh)
int pslow, pshigh; {
    register struct pagelist   *pl;

    pl = (struct pagelist *) malloc (sizeof *pl);
    if (pl == 0)
	Fatal ("Not enough memory");
    pl -> pl_alt = PageList;
    pl -> ps_low = pslow;
    pl -> ps_high = pshigh;
    PageList = pl;
}

/* Parse a string representing a list of pages.  Return 0 iff ok.  As a
   side effect, the page selection(s) is (are) prepended to PageList. */

ParsePages (s)
register char  *s; {
    register int    c,		/* current character */
                    n,		/* current numeric value */
		    innumber;	/* true => gathering a number */
    int     ps_low, ps_high,
            range,		/* true => saw a range indicator */
	    negative;		/* true => number being built is negative */

#define white(x) ((x) == ' ' || (x) == '\t' || (x) == ',')

    range = 0;
    innumber = 0;
    for (;;) {
	c = *s++;
	if ( !innumber && !range) {/* nothing special going on */
	    if (c == 0)
		return 0;
	    if (white (c))
		continue;
	}
	if (c == '-' && !innumber) {
		innumber++;
		negative++;
		n = 0;
		continue;
	}
	if (isdigit (c)) {	/* accumulate numeric value */
	    if (!innumber) {
		innumber++;
		negative = 0;
		n = c - '0';
		continue;
	    }
	    n *= 10;
	    n += negative ? '0' - c : c - '0';
	    continue;
	}
	if (c == '-' || c == ':') {/* here's a range */
	    if (range)
		return (-1);
	    if (innumber) {	/* have a lower bound */
		ps_low = n;
	    }
	    else
		ps_low = -1000000;
	    range++;
	    innumber = 0;
	    continue;
	}
	if (c == 0 || white (c)) {/* end of this range */
	    if (!innumber) {	/* no upper bound */
		ps_high = 1000000;
		if (!range)	/* no lower bound either */
		    ps_low = -1000000;
	    }
	    else {		/* have an upper bound */
		ps_high = n;
		if (!range) {	/* no range => lower bound == upper */
		    ps_low = ps_high;
		}
	    }

	    InstallPL (ps_low, ps_high);

	    if (c == 0)
		return 0;
	    range = 0;
	    innumber = 0;
	    continue;
	}
	return (-1);
    }
#undef white
}
	

/*-->ReadPostAmble*/
/**********************************************************************/
/**************************  ReadPostAmble  ***************************/
/**********************************************************************/

void
ReadPostAmble(load)
int     load;
/***********************************************************************
    This  routine  is  used  to  read  in  the  postamble  values.    It
    initializes the magnification and checks  the stack height prior  to
    starting printing the document.
***********************************************************************/
{
    FindPostAmblePtr (&postambleptr);
    if (NoSignExtend(dvifp, 1) != POST)
	Fatal ("POST missing at head of postamble");
#ifdef DEBUG
    if (Debug) fprintf (stderr, "got POST command\n");
#endif
    ppagep = NoSignExtend(dvifp, 4);
    num = NoSignExtend(dvifp, 4);
    den = NoSignExtend(dvifp, 4);
    mag = NoSignExtend(dvifp, 4);
#ifdef USEGLOBALMAG
    if( usermag > 0 && usermag != mag )
        fprintf(stderr, "DVI magnification of %d over-ridden by user mag of %d\n", mag, usermag );
#endif
    if( usermag > 0 ) mag = usermag;
#ifndef USEGLOBALMAG
    if( mag != 1000 ) fprintf(stderr, "Magnification of %d ignored.\n", mag);
#endif
    hconv = DoConv(num, den, hconvRESOLUTION);
    vconv = DoConv(num, den, vconvRESOLUTION);

    NoSignExtend(dvifp, 4);	/* height-plus-depth of tallest page */
    NoSignExtend(dvifp, 4);	/* width of widest page */
    if (NoSignExtend(dvifp, 2) >= STACKSIZE)
	Fatal ("Stack size is too small");
    NoSignExtend(dvifp, 2);	/* this reads the number of pages in */
    /* the DVI file */
#ifdef DEBUG
    if (Debug) fprintf (stderr, "now reading font defs");
#endif
    if (load) GetFontDef ();
}


/*-->SetPosn*/
/**********************************************************************/
/*****************************  SetPosn  ******************************/
/**********************************************************************/

/*-->SignExtend*/
/**********************************************************************/
/****************************  SignExtend  ****************************/
/**********************************************************************/

int
SignExtend(fp, n)   /* return n byte quantity from file fd */
register FILE *fp;  /* file pointer    */
register int n;     /* number of bytes */

{
    int n1;         /* number of bytes	    */
    register int x; /* number being constructed */

    x = getc(fp);   /* get first (high-order) byte */
    n1 = n--;
    while (n--)  {
	x <<= 8;
	x |= getc(fp);
    }

    /* NOTE: This code assumes that the right-shift is an arithmetic, rather
    than logical, shift which will propagate the sign bit right.   According
    to Kernighan and Ritchie, this is compiler dependent! */

    x<<=32-8*n1;
    x>>=32-8*n1;  /* sign extend */

#ifdef DEBUG
    if (Debug)
    {
	fprintf(stderr,"\tSignExtend(fp,%d)=%X\n",n1,x);
    }
#endif
    return(x);
}


/*-->SkipFontDef*/
/**********************************************************************/
/****************************  SkipFontDef  ***************************/
/**********************************************************************/

void
SkipFontDef(k)
int k;
{
    int a, l;
    char n[STRSIZE];

    NoSignExtend(dvifp, 4);
    NoSignExtend(dvifp, 4);
    NoSignExtend(dvifp, 4);
    a = NoSignExtend(dvifp, 1);
    l = NoSignExtend(dvifp, 1);
    GetBytes(dvifp, n, a+l);
}


/*-->Warning*/
/**********************************************************************/
/*****************************  Warning  ******************************/
/**********************************************************************/

void
Warning(fmt, a, b, c)  /* issue a warning */
char *fmt;	/* format   */
char *a, *b, *c;	/* arguments */
{
    if (G_logging == 0)
    {
        if (G_logfile)
	        G_logfp=fopen(G_Logname,"w+");
        else {
                G_logfp=stderr;
                if( G_nowarn ) return;
                }
	G_logging = 1;
	if (G_logfp == NULL) G_logging = -1;
    }

    G_errenc = TRUE;
    if (G_logging == 1)
    {
	fprintf(G_logfp, fmt, a, b, c);
	fprintf(G_logfp,"\n");
    }
}


