[fa.laser-lovers] dvi2ps source

laser-lovers@uw-beaver (07/01/85)

From: Richard Furuta <Furuta@WASHINGTON.arpa>

This is the source to dvi2ps, which was described in an earlier
note to laser-lovers.

					--Rick

# The rest of this file is a shell script which will extract:
# Description Makefile README changes.v1.02 commands.h dvi2ps.c dvi2ps.hlp tex.ps
echo x - Description
cat >Description <<'!Funky!Stuff!'
Dvi2ps is program the translates DVI files to PostScript (PostScript is a
trademark of Adobe Systems, Inc).  When the output of dvi2ps is preceded by
about 2 pages of PostScript code, TeX output can be printed on PostScript
devices (such as an Apple LaserWriter).

It uses the TeX-compatible set of 300 dpi fonts, and downloads the bitmap
description of each character, once, as it is needed, for every job (i.e., 
resident fonts  are not used).  While this sounds expensive, it is not too 
bad.  After the conversion to PostScript is done, and considering "normal 
documents" and 9600 baud communication, the first page can take a minute or 
so to transmit and print.  Thereafter, pages are usually printed faster.
Simple documents of 20 & 30 pages have printed at an overall average of
3.2 pages/minute (it is unlikely that you will ever get substantially 
higher than this with the program as it currently stands).  More typical
rates will be 2.5 pages/min.  Conversion time is extra, of course, but
does not seem to be excessive.

Dvi2ps currently runs on Apollo (AEGIS) and Vax 4.2BSD machines (and shortly
Macintosh XL with MacWorks).

There are many problems:

  1. It is not very clever about which fonts and characters to download on
     a per-job basis, except that each character is sent only once, just before
     it is needed.  All character and fonts are then made resident on the printer
     until the end of the job.  This consumes more memory on the printer (at least 
     on the Apple LaserWriter) than is necessary, and can limit the size of the
     job than can be printed.  "Simple" 50 page documents can be printed
     with room to spare (I suspect the limit is in the range of 70-100 pages for
     these, but we haven't tried any that large yet).  On the other hand,
     a section out of the LaTeX test files (manual) that uses 30 or more
     different fonts, some of them very large, was limited to 30 pages.
     Dvi2ps has -from and -to options to extract ranges of pages.

  2. The resulting PostScript files are very large (they can easily be 5 times
     the size of the DVI file).

  3. Character positioning is not calculated in the "official" dvitype manner,
     and so there *might* be *VERY* small anomolies.  However, care is taken,
     and the result is quite acceptable (at least to many untrained eyes).
     In fact, positioning is better than some other common processors, and
     no anomolies have as yet been noticed.

In summary, it was quite easy to develop and will serve us well until something
better comes along.
!Funky!Stuff!
echo x - Makefile
cat >Makefile <<'!Funky!Stuff!'
#
# where are the bitmaps stored?
FONTAREA=/usr/lib/tex/fonts

CFLAGS = -fsingle -DFONTAREA=\"${FONTAREA}\" -O

all: dvi2ps

dvi2ps:	dvi2ps.o
	cc -o dvi2ps dvi2ps.o
dvi2ps.o:	dvi2ps.c
	cc -c ${CFLAGS} dvi2ps.c
!Funky!Stuff!
echo x - README
cat >README <<'!Funky!Stuff!'
The use of this program may not be readily apparent.  If you are using
TranScript, and your printer's name is "ps", you would use a command
sequence that looked something like this:

	% tex myfile
	% dvi2ps myfile > myfile.ps
	% cat tex.ps myfile.ps | lpr -Pps

The first few pages will print in a very very slow fashion while the fonts
are being defined.  Printing speeds up a little as you get further down the
document.

(Notes added by Richard Furuta)
!Funky!Stuff!
echo x - changes.v1.02
cat >changes.v1.02 <<'!Funky!Stuff!'
Changes since v. 1.01:
----------------------


11-Jun-85 (nmh)   - Spacing problems in long strings (demonstrated by 
          Les Earnest's "taste test" trial.

      - changed to output char spacing width as a floating point number,
        rather than as an integer rounded to pixels.  This was causing problems
        in spacings of long strings of characters - the truncation errors were
        accumulating.

12-Jun-85 Changed to process DVI pages in reverse order.  That way, they
          come out stacked in correct order.  Added "-r" option to defeat
          this.

13-Jun-85 reduced size of arrays in PS dictionaries to 128 entries (saves
          2K bytes in LaserWriter per font)

13-Jun-85 SetFntNum wasn't always getting called on first pass through
          the DVI page (fixed at opcodes FNT1..FNT4).

          If -p (no preload) option is given, we MUST process DVI pages in 
          forward order, thus this option forces "-r" option.

          Changed help file for -r option.

          With -p option (no preload), font files were getting loaded and 
          opened more often than necessary.   added fn HasBeenRead().

          Warn about ignored magnifications.

14-Jun-85 Changed to emit font-dictionary-creating command just before
          the first character bitmap of that font gets output.  This allows
          more pages to be printed when you extract a subrange of the DVI
          file, as fonts not referred to in thos pages will not be created.
          I guess this also makes the -p option less (not?) necessary.

          Added -m0, -mh, -m1, -m2, -m3, -m4 options to specify magnifications
          in terms of magsteps.
          

17-Jun-85 In EmitChar() changed the following line:
                sl = (unsigned char *)(ce.where.pixptr + i*nwpl);
          to:
                sl = (unsigned char *)(ce.where.address.pixptr + i*nwpl);
          How did that ever work??!!??

          In DecodeArgs(), removed call to tolower() -- replaced with direct code.

          These two were from Furuta, and from compiling on Vax.

18-Jun-85 Was not handling missing fonts properly - would forget to create
          a dictionary, then later would expect to make that forgotten dictionary
          the current font.  Fixed by adding code to completely ignore
          characters pertaining to missing fonts (in SetFntNum(), SetChar(),
          SetString()) -- the intent is to leave the proper size gaps in
          the document.

19-Jun-85 Trivial change to the way hex values of bytes written.  Got rid
          of silly big table (a Lisa with MacWorks didn't build it correctly).
!Funky!Stuff!
echo x - commands.h
cat >commands.h <<'!Funky!Stuff!'
/*
 *
 * $Revision: 1.1 $
 * $Log:	commands.h,v $
 * Revision 1.1  83/11/23  10:56:00  mds
 * Initial revision
 * 
 *
 */
#define  SETC_000    0
#define  SETC_001    1
#define  SETC_002    2
#define  SETC_003    3
#define  SETC_004    4
#define  SETC_005    5
#define  SETC_006    6
#define  SETC_007    7
#define  SETC_008    8
#define  SETC_009    9
#define  SETC_010   10
#define  SETC_011   11
#define  SETC_012   12
#define  SETC_013   13
#define  SETC_014   14
#define  SETC_015   15
#define  SETC_016   16
#define  SETC_017   17
#define  SETC_018   18
#define  SETC_019   19
#define  SETC_020   20
#define  SETC_021   21
#define  SETC_022   22
#define  SETC_023   23
#define  SETC_024   24
#define  SETC_025   25
#define  SETC_026   26
#define  SETC_027   27
#define  SETC_028   28
#define  SETC_029   29
#define  SETC_030   30
#define  SETC_031   31
#define  SETC_032   32
#define  SETC_033   33
#define  SETC_034   34
#define  SETC_035   35
#define  SETC_036   36
#define  SETC_037   37
#define  SETC_038   38
#define  SETC_039   39
#define  SETC_040   40
#define  SETC_041   41
#define  SETC_042   42
#define  SETC_043   43
#define  SETC_044   44
#define  SETC_045   45
#define  SETC_046   46
#define  SETC_047   47
#define  SETC_048   48
#define  SETC_049   49
#define  SETC_050   50
#define  SETC_051   51
#define  SETC_052   52
#define  SETC_053   53
#define  SETC_054   54
#define  SETC_055   55
#define  SETC_056   56
#define  SETC_057   57
#define  SETC_058   58
#define  SETC_059   59
#define  SETC_060   60
#define  SETC_061   61
#define  SETC_062   62
#define  SETC_063   63
#define  SETC_064   64
#define  SETC_065   65
#define  SETC_066   66
#define  SETC_067   67
#define  SETC_068   68
#define  SETC_069   69
#define  SETC_070   70
#define  SETC_071   71
#define  SETC_072   72
#define  SETC_073   73
#define  SETC_074   74
#define  SETC_075   75
#define  SETC_076   76
#define  SETC_077   77
#define  SETC_078   78
#define  SETC_079   79
#define  SETC_080   80
#define  SETC_081   81
#define  SETC_082   82
#define  SETC_083   83
#define  SETC_084   84
#define  SETC_085   85
#define  SETC_086   86
#define  SETC_087   87
#define  SETC_088   88
#define  SETC_089   89
#define  SETC_090   90
#define  SETC_091   91
#define  SETC_092   92
#define  SETC_093   93
#define  SETC_094   94
#define  SETC_095   95
#define  SETC_096   96
#define  SETC_097   97
#define  SETC_098   98
#define  SETC_099   99
#define  SETC_100  100
#define  SETC_101  101
#define  SETC_102  102
#define  SETC_103  103
#define  SETC_104  104
#define  SETC_105  105
#define  SETC_106  106
#define  SETC_107  107
#define  SETC_108  108
#define  SETC_109  109
#define  SETC_110  110
#define  SETC_111  111
#define  SETC_112  112
#define  SETC_113  113
#define  SETC_114  114
#define  SETC_115  115
#define  SETC_116  116
#define  SETC_117  117
#define  SETC_118  118
#define  SETC_119  119
#define  SETC_120  120
#define  SETC_121  121
#define  SETC_122  122
#define  SETC_123  123
#define  SETC_124  124
#define  SETC_125  125
#define  SETC_126  126
#define  SETC_127  127
#define  SET1          128
#define  SET2          129
#define  SET3          130
#define  SET4          131
#define  SET_RULE      132
#define  PUT1          133
#define  PUT2          134
#define  PUT3          135
#define  PUT4          136
#define  PUT_RULE      137
#define  NOP           138
#define  BOP           139
#define  EOP           140
#define  PUSH          141
#define  POP           142
#define  RIGHT1        143
#define  RIGHT2        144
#define  RIGHT3        145
#define  RIGHT4        146
#define  W0            147
#define  W1            148
#define  W2            149
#define  W3            150
#define  W4            151
#define  X0            152
#define  X1            153
#define  X2            154
#define  X3            155
#define  X4            156
#define  DOWN1         157
#define  DOWN2         158
#define  DOWN3         159
#define  DOWN4         160
#define  Y0            161
#define  Y1            162
#define  Y2            163
#define  Y3            164
#define  Y4            165
#define  Z0            166
#define  Z1            167
#define  Z2            168
#define  Z3            169
#define  Z4            170
#define  FONT_00    171
#define  FONT_01    172
#define  FONT_02    173
#define  FONT_03    174
#define  FONT_04    175
#define  FONT_05    176
#define  FONT_06    177
#define  FONT_07    178
#define  FONT_08    179
#define  FONT_09    180
#define  FONT_10    181
#define  FONT_11    182
#define  FONT_12    183
#define  FONT_13    184
#define  FONT_14    185
#define  FONT_15    186
#define  FONT_16    187
#define  FONT_17    188
#define  FONT_18    189
#define  FONT_19    190
#define  FONT_20    191
#define  FONT_21    192
#define  FONT_22    193
#define  FONT_23    194
#define  FONT_24    195
#define  FONT_25    196
#define  FONT_26    197
#define  FONT_27    198
#define  FONT_28    199
#define  FONT_29    200
#define  FONT_30    201
#define  FONT_31    202
#define  FONT_32    203
#define  FONT_33    204
#define  FONT_34    205
#define  FONT_35    206
#define  FONT_36    207
#define  FONT_37    208
#define  FONT_38    209
#define  FONT_39    210
#define  FONT_40    211
#define  FONT_41    212
#define  FONT_42    213
#define  FONT_43    214
#define  FONT_44    215
#define  FONT_45    216
#define  FONT_46    217
#define  FONT_47    218
#define  FONT_48    219
#define  FONT_49    220
#define  FONT_50    221
#define  FONT_51    222
#define  FONT_52    223
#define  FONT_53    224
#define  FONT_54    225
#define  FONT_55    226
#define  FONT_56    227
#define  FONT_57    228
#define  FONT_58    229
#define  FONT_59    230
#define  FONT_60    231
#define  FONT_61    232
#define  FONT_62    233
#define  FONT_63    234
#define  FNT1          235
#define  FNT2          236
#define  FNT3          237
#define  FNT4          238
#define  XXX1          239
#define  XXX2          240
#define  XXX3          241
#define  XXX4          242
#define  FNT_DEF1      243
#define  FNT_DEF2      244
#define  FNT_DEF3      245
#define  FNT_DEF4      246
#define  PRE           247
#define  POST          248
#define  POST_POST     249
!Funky!Stuff!
echo x - dvi2ps.c
cat >dvi2ps.c <<'!Funky!Stuff!'
#define VERSION "1.02"

/*
 *
 * 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.
 *
 */

/* 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 (origin at lower
 * left), and in integer units of "dots" (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.  This program does NOT automatically include it.
 */


/* 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
 */


/**********************************************************************/
/************************  Global Definitions  ************************/
/**********************************************************************/

/* This version purports to drive a PostScript device (slowly) */


typedef int BOOLEAN;
#define NEW(A) ((A *) malloc(sizeof(A)))
#define DEBUG   1			/* for massive printing of input */
					/* trace information; select by -d */
					/* option after filename: */
					/* dviview filename -d */
#ifdef DEBUG
int Debug = 0;
#endif
                          /* to enable statistics reporting via -s option */
#define STATS

#define BINARYOPEN fopen		/* byte-oriented host version */

#define ARITHRSHIFT 1                   /* define if ">>" operator is a
                                           sign-propagating arithmetic
                                           right shift */
#define USEGLOBALMAG 1			/* when defined, the dvi global
   					   magnification is applied */

/* We leave USEGLOBALMAG undefined because currently we have a limited
   number font magnifications (at 300dpi) available and  if it  is
   defined, any dvi file is as likely as not to fail */
#undef USEGLOBALMAG

                        /* define for "optimal" relative postioning, rather
                           than absolute.  Relative can reduce size of postcript
                           output 20% (and reduce print time by almost as much */
#define USERELPOS 1 

#define  DVIFORMAT        2
#define  FALSE            0
#define  FIRSTPXLCHAR     0
#ifndef FONTAREA
#define  FONTAREA         "/local/tex/pxl300"
#endif
#define  LASTPXLCHAR    127
#define  MAXOPEN         50  /* limit on number of open PXL files */
#define  NPXLCHARS      128
#define  PXLID         1001
#define  READ             4  /* for access() */
#define  RESOLUTION      300
#define  hconvRESOLUTION 300
#define  vconvRESOLUTION 300
#define  PTOP           3300
#define  STACKSIZE      100
#define  STRSIZE        257
#define  TRUE             1
#define  NONEXISTANT     -1   /* offset for PXL files not found */
#define  NOFILE        (FILE *)-1


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

#include "commands.h"
#include <signal.h>
#include <stdio.h>
#include <ctype.h>

char *getenv();
char *index();
char *malloc();
int  free();
char *rindex();
char *sprintf();
char *strcpy();

                        /* output a formatted string */
#define EMIT      printf
                        /* output a simple string */
#define EMITS(s)  fputs(s,stdout)
                        /* output an escaped octal number */
#define EMITO(c)  PutOct(c)
                        /* output a decimal integer */
#define EMITN(n)  PutInt(n)
                        /* output a byte value in Hex */
#define EMITH(h)  putchar(*(digit+((h>>4)&0xF))),\
                  putchar(*(digit+(h&0xF)))
                        /* output a single character */
#define EMITC(c)  putchar(c)
                        /* output a scaled X dimension */
#define EMITX(x)  PutInt(PixRound(x,hconv))
                        /* output a scaled Y dimension */
#define EMITY(y)  PutInt(PixRound(y,vconv))

                                   /* formatted i/o was killing us, so build some tables */
char    *digit = "0123456789ABCDEF";

int dummyInt;
short dummyShort;
char dummyChar;

/**********************************************************************/
/*************************  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    DecodeArgs();
void    DoSpecial();
void    EmitChar();
void	Fatal();
void	FindPostAmblePtr();
void	GetBytes();
void	GetFontDef();
int     HasBeenRead();
void	LoadRast();
void	MoveDown();
void	MoveOver();
int     NoSignExtend();         /* see cautionary note in code, re arithmetic vs logical shifts */
void	OpenFontFile();
int	PixRound();
void    PutInt();
int	ReadFontDef();
void	ReadPostAmble();
void	SetChar();
void	SetFntNum();
void    SetPosn();
void	SetRule();
void    SetString();
int     SignExtend();           /* see cautionary note in code, re arithmetic vs logical shifts */
void	SkipFontDef();
void	Warning();


/**********************************************************************/
/***********************  Font Data Structures  ***********************/
/**********************************************************************/

struct char_entry {		/* character entry */
   unsigned short width, height;/* width and height in pixels */
   short xOffset, yOffset;      /* x offset and y offset in pixels */
   struct {
       int isloaded;
       union {
	   int fileOffset;
	   long *pixptr; } address;
       } where;
   int tfmw;			/* TFM width */
   };

struct font_entry {  /* font entry */
   int k, c, s, d, a, l;
   char n[STRSIZE];	/* FNT_DEF command parameters  */
   int font_space;	/* computed from FNT_DEF s parameter        */
   int font_mag;	/* computed from FNT_DEF s and d parameters */
   char psname[STRSIZE]; /* PostScript name of the font             */
   char name[STRSIZE];	/* full name of PXL file                    */
   FILE *font_file_id;  /* file identifier (NOFILE if none)         */
   int magnification;	/* magnification read from PXL file         */
   int designsize;	/* design size read from PXL file           */
   struct char_entry ch[NPXLCHARS];/* character information         */
   struct font_entry *next;
   int ncdl;            /* # of different chars actually downloaded */
#ifdef STATS
   int nbpxl;           /* # of bytes of PXL data downloaded        */
   int ncts;            /* total # of characters typeset */
#endif
   };

struct pixel_list
{
    FILE *pixel_file_id;        /* file identifier                          */
    int use_count;              /* count of "opens"                         */
    };



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

int   FirstPage = -1000000;     /* first page to print (uses count0)   */
int   LastPage = 1000000;       /* last page to print                    */

int   G_errenc = FALSE;	        /* has an error been encountered?          */
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   hconv, vconv;		/* converts DVI units to pixels             */
int   den;			/* denominator specified in preamble        */
FILE *dvifp  = NULL;		/* DVI file pointer                         */
int   PreLoad = TRUE;	        /* preload the font descriptions?	     */
struct font_entry *prevfont=NULL;  /* font_entry pointer, previous character */
struct font_entry *fontptr;     /* font_entry pointer                       */
struct font_entry *hfontptr=NULL;/* font_entry pointer                      */
int   h;				/* current horizontal position              */
int   hh = 0;                           /* current h on device */
int   v;				/* current vertical position                */
int   vv = 0;                           /* current v on device */
int   mag;			/* magnification specified in preamble      */
int   nopen;			/* number of open PXL files                 */
int   num;			/* numerator specified in preamble          */
struct font_entry *pfontptr = NULL; /* previous font_entry pointer          */
struct pixel_list pixel_files[MAXOPEN+1];
                                /* list of open PXL file identifiers        */

long  postambleptr;		/* Pointer to the postamble                 */
FILE *pxlfp;			/* PXL file pointer                         */
char *PXLpath;			/* PXL path name for search		    */
long  ppagep;	                /* previous page pointer		     */

int   Reverse = TRUE;         /* process DVI pages in reverse order ? */

#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 STATS

int usermag = 0;              /* user specified magnification */

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

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

{
    struct stack_entry {  /* stack entry */
	int h, v, w, x, y, z;  /* 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		     */

    nopen = 0;
    strcpy(G_progname, argv[0]);

    PXLpath = FONTAREA;       /* default font area */

    DecodeArgs( argc, argv );

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

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

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


    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);
            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);

	    h = v = w = x = y = z = 0;
            hh = vv = 0;
	    sp = 0;
	    fontptr = NULL;
            prevfont = NULL;

            if( count[0] < FirstPage || count[0] > LastPage )
                SkipMode = TRUE;
            else
                SkipMode = FALSE;

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

            if( !SkipMode ) {
                if( PassNo == 0) {
                        EMIT("%d @bop0\n", count[0]);
#ifdef STATS
                        if( Stats ) {
                                Sndc0 = Sndc;
                                Stnc0 = Stnc;
                                Snbpx0 = Snbpxl;
                                }
                        else 
#endif
                                if( (count[0] % 10) == 1 ) fprintf(stderr,"\n");
                        fprintf(stderr, "[%d", count[0] );
                        }
                else
                        EMIT("%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("@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
                        fprintf(stderr,"] ");
                    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;
	    sp++;
	    break;

	case POP:
	    --sp;
	    if (sp < 0)
		Fatal("stack underflow");
	    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:
            if (!SkipMode) {
                SetFntNum(NoSignExtend(dvifp,command-FNT1+1), 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==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;

    EMIT("@end\n");
    fprintf(stderr,"\n");

    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) {
        for( p=hfontptr; p!=NULL; p=p->next )
                fprintf(stderr, "%s - %d total ch,  %d diff ch,  %d pxl bytes\n",     
                                p->psname, p->ncts, p->ncdl, p->nbpxl );
        fprintf(stderr, "\nTotal number of characters typeset: %d\n", Stnc);
        fprintf(stderr, "Number of different characters downloaded: %d\n", Sndc);
        fprintf(stderr, "Number of bytes of pxl data downloaded: %d\n", Snbpxl);
        fprintf(stderr, "Optimal # of bytes of pxl data: %d\n", Sonbpx);
        }
#endif

    AbortRun(G_errenc);
}


/*-->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 filename[STRSIZE]; /* 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) {
#ifdef DEBUG
		case 'd':	/* d selects Debug output */
		    Debug = TRUE;
		    break;
#endif

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

                case 'a':       /* a selects different pxl font area */
                    PXLpath = argv[++argind];
                    break;

                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 '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;
#ifdef USEGLOBALMAG
                case 'm':       /* specify magnification to use */
                    switch( tolower(*++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;
                    default: Fatal("%c is a bad mag step\n", *tcp);
                    }
                    break;
#endif
                case 'r':
                    Reverse = FALSE;
                    break;
#ifdef STATS
                case 's':
                    Stats = TRUE;
                    break;
#endif
		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 += 1;
                }
        
            strcpy(curname, tcp);
            tcp1 = rindex(tcp, '.');   /* split into file name + extension */
            if (tcp1 == NULL)
                strcat(curname, ".dvi");
        
            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 [-p] [-s] [-r] [-f n] [-t n] [-m{0|h|1|2|3|4|  mag] [-a fontarea] dvifile\n\n", 
                G_progname);
	AbortRun(1);
        }
}


/*-->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));
}


/*-->DoSpecial*/
/*********************************************************************/
/*****************************  DoSpecial  ***************************/
/*********************************************************************/

void
DoSpecial( str, n )          /* copy special file straight through */
char    str[];
int n;
{
        FILE *spfp;
        char t;

        str[n] = '\0';
        if( (spfp=fopen(str,"r")) == NULL ) {
                fprintf(stderr,"Unable to open special file %d\n", str );
                return;
                }
        fprintf(stderr," [%s", str);
        SetPosn(h, v);
        EMITS("@beginspecial\n");
        while( (t = getc(spfp)) != EOF ) {
                EMITC(t);
                }              
        EMITS("@endspecial\n");
        fclose(spfp);
        fprintf(stderr,"]");
}


/*-->EmitChar*/
/**********************************************************************/
/****************************  EmitChar  ******************************/
/**********************************************************************/


void
EmitChar(c, ce)              /* output a character bitmap */
int c;
struct char_entry *ce;
{
        int i;
        register int j;
        register unsigned char *sl;
        register int cc;
        int nbpl, nwpl;
        float cw;       /* char width, in "dots" - we rely on PostScript maintaining sufficient accuracy */

                        /* Output in PostScript coord system (y +ive up, x +ive right)
                           (0,0) of char bitmap at lower left.  Output scan lines
                           from bottom to top */

        if( fontptr->ncdl == 0 )      /* open font dict before first char */
                EMIT("[ %d ] /%s @newfont\n", fontptr->font_mag, fontptr->psname );
 
        if( fontptr != prevfont ) {   /* because this isn't done on pass 0 */
                EMIT("%s @sf\n", fontptr->psname);
                prevfont = fontptr;
                }
        EMITS("[<");
        cc = 2;
        nbpl = (ce->width + 7) >> 3;
        nwpl = (ce->width + 31) >> 5;
        for(i = ce->height-1;  i >= 0;  i--) {
                sl = (unsigned char *)(ce->where.address.pixptr + i*nwpl);
                for(j = 0;  j < nbpl;  j++, sl++) {
                        if( cc > 100 ) {
                                EMITS("\n  ");   cc = 2; }
                        EMITH(*sl);
                        cc += 2;
                        }
                }
        cw = (float)ce->tfmw / (float)hconv;
        EMIT("> %d %d %d %d %.3f] %d @dc\n", 
             nbpl<<3, ce->height, ce->xOffset, (((int)ce->height)-ce->yOffset)-1, cw,
             c);
        fontptr->ncdl += 1;

#ifdef STATS
        Snbpxl += nbpl*ce->height;
        fontptr->nbpxl += nbpl*ce->height;
        Sonbpx += (ce->width*ce->height + 7) >> 3;
        Sndc += 1;
#endif
}


/*-->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");
    AbortRun(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)) {
	switch (byte) {
	case FNT_DEF1:
	    ReadFontDef (NoSignExtend(dvifp, 1));
	    break;
	case FNT_DEF2:
	    ReadFontDef (NoSignExtend(dvifp, 2));
	    break;
	case FNT_DEF3:
	    ReadFontDef (NoSignExtend(dvifp, 3));
	    break;
	case FNT_DEF4:
	    ReadFontDef (NoSignExtend(dvifp, 4));
	    break;
	default:
	    Fatal ("Bad byte value in font defs");
	    break;
	}
    }
    if (byte != POST_POST)
	Fatal ("POST_POST missing after fontdefs");
}


/*-->HasBeenRead*/
/**********************************************************************/
/***************************  HasBeenRead  ****************************/
/**********************************************************************/

int
HasBeenRead(k)
int k;
{
    struct font_entry *ptr;

    ptr = hfontptr;
    while ((ptr!=NULL) && (ptr->k!=k))
	ptr = ptr->next;
    return( ptr != NULL );
}


/*-->MoveDown*/
/**********************************************************************/
/****************************  MoveDown  ******************************/
/**********************************************************************/

void
MoveDown(a)
int a;
{
    v += a;
}


/*-->MoveOver*/
/**********************************************************************/
/****************************  MoveOver  ******************************/
/**********************************************************************/

void
MoveOver(b)
int b;
{
    h += b;
}


/*-->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);
}
/*-->OpenFontFile*/
/**********************************************************************/
/************************** OpenFontFile  *****************************/
/**********************************************************************/


void
OpenFontFile()
/***********************************************************************
    The original version of this dvi driver reopened the font file  each
    time the font changed, resulting in an enormous number of relatively
    expensive file  openings.   This version  keeps  a cache  of  up  to
    MAXOPEN open files,  so that when  a font change  is made, the  file
    pointer, pxlfp, can  usually be  updated from the  cache.  When  the
    file is not found in  the cache, it must  be opened.  In this  case,
    the next empty slot  in the cache  is assigned, or  if the cache  is
    full, the least used font file is closed and its slot reassigned for
    the new file.  Identification of the least used file is based on the
    counts of the number  of times each file  has been "opened" by  this
    routine.  On return, the file pointer is always repositioned to  the
    beginning of the file.

***********************************************************************/
{
    register int i,least_used,current;

#ifdef DEBUG
    if (Debug) printf("Open Font file\n");
#endif
    if (pfontptr == fontptr)
        return;                 /* we need not have been called */

    for (current = 1;
	(current <= nopen) &&
	    (pixel_files[current].pixel_file_id != fontptr->font_file_id);
	++current)
	;                       /* try to find file in open list */

    if (current <= nopen)       /* file already open */
    {
	if( (pxlfp = pixel_files[current].pixel_file_id) != NOFILE )
	        fseek(pxlfp,0,0);	/* reposition to start of file */
    }
    else                        /* file not in open list */
    {
        if (nopen < MAXOPEN)    /* just add it to list */
            current = ++nopen;
	else                    /* list full -- find least used file, */
	{                       /* close it, and reuse slot for new file */
	    least_used = 1;
            for (i = 2; i <= MAXOPEN; ++i)
	        if (pixel_files[least_used].use_count >
                    pixel_files[i].use_count)
		    least_used = i;
            if (pixel_files[least_used].pixel_file_id != NOFILE) {
                FILE *fid;
                struct font_entry *fp;

                fid = pixel_files[least_used].pixel_file_id;
                fp=hfontptr;    /* mark file as being closed in the entry */                 
                while (fp!=NULL && fp->font_file_id != fid) 
                        fp = fp->next;
                if (fp==NULL)
                        Fatal("Open file %x not found in font entry list.\n", fid);
                else {
                        fp->font_file_id = NULL;
#ifdef STATS
                        if (Stats)
                                fprintf(stderr, "PXL file %s closed.\n", fp->name);
#endif STATS
                        }
 	        fclose( fid );
                }
	    current = least_used;
        }
        if ((pxlfp=BINARYOPEN(fontptr->name,"r")) == NULL) {
	    Warning("PXL file %s could not be opened",fontptr->name);
            pxlfp = NOFILE;
            }
        else {
#ifdef STATS
            if (Stats) 
                fprintf(stderr, "PXL file %s opened.\n", fontptr->name);
#endif STATS
            }
	pixel_files[current].pixel_file_id = pxlfp;
	pixel_files[current].use_count = 0;
    }
    pfontptr = fontptr;			/* make previous = current font */
    fontptr->font_file_id = pxlfp;	/* set file identifier */
    pixel_files[current].use_count++;	/* update reference count */
}


/*-->PixRound*/
/**********************************************************************/
/*****************************  PixRound  *****************************/
/**********************************************************************/

int
PixRound(x, conv)	/* return rounded number of pixels */
register int x;		/* in DVI units     */
int conv;		/* conversion factor */
{
    return((int)((x + (conv >> 1)) / conv));
}


/*-->PutInt*/
/**********************************************************************/
/*****************************  PutInt  *******************************/
/**********************************************************************/

void
PutInt(n)               /* output an integer followed by a space */
register int n;
{
    char buf[10];
    register char *b;

    if( n == 0 )
        EMITC('0'); 
    else {
        if( n < 0 ) {
            EMITC('-');
            n = -n;
            }
    
        for(b=buf;  n>0;  ) {
            *b++ = digit[n%10];
            n /= 10;
            }
    
        for( ; b>buf; )
            EMITC(*--b);
        }

    EMITC(' ');
}


/*-->PutOct*/
/**********************************************************************/
/*****************************  PutOct  *******************************/
/**********************************************************************/

void
PutOct(n)               /* output an 3 digit octal number preceded by a "\" */
register int n;
{                  
    EMITC( '\\' ); 
    EMITC( digit[(n&0300)>>6] );
    EMITC( digit[(n&0070)>>3] ); 
    EMITC( digit[n&0007] );
}


/*-->ReadFontDef*/
/**********************************************************************/
/****************************  ReadFontDef  ***************************/
/**********************************************************************/

int
ReadFontDef(k)
int k;
{
    int t, i;
    register struct font_entry *tfontptr;    /* temporary font_entry pointer   */
    register struct char_entry *tcharptr;/* temporary char_entry pointer  */
    char *direct, *tcp, *tcp1;
    int found;
    char curarea[STRSIZE];

    if ((tfontptr = NEW(struct font_entry)) == NULL)
	Fatal("can't malloc space for font_entry");
    tfontptr->next = hfontptr;
    tfontptr->font_file_id = NULL;
    fontptr = hfontptr = tfontptr;

    tfontptr->ncdl = 0;
#ifdef STATS
    tfontptr->nbpxl = 0;
    tfontptr->ncts = 0;
#endif

    tfontptr->k = k;
    tfontptr->c = NoSignExtend(dvifp, 4); /* checksum */
    tfontptr->s = NoSignExtend(dvifp, 4); /* space size */
    tfontptr->d = NoSignExtend(dvifp, 4); /* design size */
    tfontptr->a = NoSignExtend(dvifp, 1); /* area length for font name */
    tfontptr->l = NoSignExtend(dvifp, 1); /* device length */
    GetBytes(dvifp, tfontptr->n, tfontptr->a+tfontptr->l);
    tfontptr->n[tfontptr->a+tfontptr->l] = '\0';
    tfontptr->font_space = tfontptr->s/6; /* never used */
    tfontptr->font_mag = (int)((ActualFactor((int)(((float)tfontptr->s/
    			(float)tfontptr->d)*1000.0 + 0.5)) * 
#ifdef USEGLOBALMAG
			ActualFactor(mag) *
#endif
			(float)RESOLUTION * 5.0) + 0.5);
    sprintf(tfontptr->psname, "%s.%d", tfontptr->n, tfontptr->font_mag);

    if (tfontptr->a != 0) {
	sprintf(tfontptr->name, "%s.%dpxl", tfontptr->n, tfontptr->font_mag);
    } else {
	direct = PXLpath;
	found = FALSE;
        do { 
	    tcp = index(direct, ':');
	    if (tcp == NULL) tcp = strlen(direct) + direct;
	    strncpy(curarea, direct, tcp-direct);
	    tcp1 = curarea + (tcp - direct);
	    *tcp1++ = '/';
	    *tcp1++ = '\0';

	    sprintf(tfontptr->name, "%s%s.%dpxl", curarea, tfontptr->n, tfontptr->font_mag);
	    found = (access(tfontptr->name, READ) == 0);
	    if (*tcp) direct = tcp + 1; else direct = tcp;
	} while ( !found && *direct != '\0');
    }
    if (tfontptr != pfontptr)
	OpenFontFile();
    if ( pxlfp == NOFILE ) {                /* allow missing pxl files */
        tfontptr->magnification = 0;
        tfontptr->designsize = 0;
        for (i = FIRSTPXLCHAR; i <= LASTPXLCHAR; i++) {
	    tcharptr = &(tfontptr->ch[i]);
	    tcharptr->width = 0;
	    tcharptr->height = 0;
	    tcharptr->xOffset= 0;
	    tcharptr->yOffset = 0;
	    tcharptr->where.isloaded = FALSE;
	    tcharptr->where.address.fileOffset = NONEXISTANT;
	    tcharptr->tfmw = 0;
            }
        return;
        }

    if ((t = NoSignExtend(pxlfp, 4)) != PXLID)
	Fatal("PXL ID = %d, can only process PXL ID = %d files",
	      t, PXLID);
    fseek(pxlfp, -20, 2);
    t = NoSignExtend(pxlfp, 4);
    if ((tfontptr->c != 0) && (t != 0) && (tfontptr->c != t))
	Warning("font = \"%s\",\n-->font checksum = %d,\n-->dvi checksum = %d",
	        tfontptr->name, tfontptr->c, t);
    tfontptr->magnification = NoSignExtend(pxlfp, 4);
    tfontptr->designsize = NoSignExtend(pxlfp, 4);

    fseek(pxlfp, NoSignExtend(pxlfp, 4) * 4, 0);

    for (i = FIRSTPXLCHAR; i <= LASTPXLCHAR; i++) {
	tcharptr = &(tfontptr->ch[i]);
	tcharptr->width = NoSignExtend(pxlfp, 2);
	tcharptr->height = NoSignExtend(pxlfp, 2);
	tcharptr->xOffset= SignExtend(pxlfp, 2);
	tcharptr->yOffset = SignExtend(pxlfp, 2);
	tcharptr->where.isloaded = FALSE;
	tcharptr->where.address.fileOffset = NoSignExtend(pxlfp, 4) * 4;
	tcharptr->tfmw = ((float)NoSignExtend(pxlfp, 4)*(float)tfontptr->s) /
	    (float)(1<<20);
    }
}


/*-->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);
    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 ();
}


/*-->SetChar*/
/**********************************************************************/
/*****************************  SetChar  ******************************/
/**********************************************************************/

int buffer[8];

LoadAChar(c, ptr)
int c;
register struct char_entry *ptr;
{
    long *pr;
    register int nints;

    if (ptr->where.address.fileOffset == NONEXISTANT) {
	ptr->where.address.pixptr = NULL;
        ptr->where.isloaded = TRUE;
	return;
        }

    OpenFontFile();
    fseek(pxlfp, ptr->where.address.fileOffset, 0);
    nints = ((ptr->width + 31) >> 5) * ptr->height;
    if( (pr = (long *)malloc( nints*sizeof(long) )) == NULL )
        Fatal("Unable to allocate memory for char\n");
    fread(pr, 4, nints, pxlfp);
    ptr->where.address.pixptr = pr;
    ptr->where.isloaded = TRUE;

    EmitChar(c, ptr);
        /* we should really free the space used by the PXL data after this
           point, but it is not large, and besides, we may want to be
           more clever in the future, about sending bitmaps.  So keep
           the data around */
}

void
SetChar(c, command, PassNo)
int c, command, PassNo;
{
    register struct char_entry *ptr;  /* temporary char_entry pointer */
    int k;

    ptr = &(fontptr->ch[c]);
    if (!ptr->where.isloaded) LoadAChar(c, ptr);
    if (PassNo==0) return;

    SetPosn(h,v);
    if (fontptr->font_file_id != NOFILE) {      /* ignore missing fonts */
        EMITN(c); EMITS("c\n");
        hh += ptr->tfmw;
        }

    if (command <= SET4)
        h += ptr->tfmw;

#ifdef STATS
    Stnc += 1;
    fontptr->ncts += 1;
#endif
}


/*-->SetFntNum*/
/**********************************************************************/
/****************************  SetFntNum  *****************************/
/**********************************************************************/

void
SetFntNum(k, Emitting)
int k, Emitting;

/*  this routine is used to specify the font to be used in printing future
    characters */

{
    fontptr = hfontptr;
    while ((fontptr!=NULL) && (fontptr->k!=k))
	fontptr = fontptr->next;
    if (fontptr == NULL)
	Fatal("font %d undefined", k);
    if (Emitting && (fontptr->font_file_id != NOFILE) ) 
        EMIT("%s @sf\n", fontptr->psname);
}


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

void
SetPosn(x, y)           /* output a positioning command */
int x, y;
{
        int rx,ry;
#ifdef USERELPOS
        if (y == vv) {  /* use relative movement if just moving horizontally */
            if ( x != hh ) {
                EMITN(rx=PixRound(x-hh,hconv));
                EMITS("r ");
                hh += rx*hconv;
                }
            }
        else {
#endif USERELPOS
            EMITN(rx=PixRound(x,hconv));
            EMITN(PTOP-(ry=PixRound(y,vconv)));
            EMITS("p ");
            hh = rx*hconv;      /* must know where device "really" is horizontally, for rel. posning. */
            vv = y;             /* but we always use direct positioning for vertical movement */
#ifdef USERELPOS
            }
#endif USERELPOS
}


/*-->SetRule*/
/**********************************************************************/
/*****************************  SetRule  ******************************/
/**********************************************************************/

void
SetRule(a, b, Set)
int a, b;
BOOLEAN Set;

{	    /*	 this routine will draw a rule */

    if( a > 0 && b > 0 ) {
        SetPosn(h,v);                   /* lower left corner */
        EMITN(PixRound(b,hconv));       /* width */
        EMITN(PixRound(a,vconv));       /* height */
        EMITS("ru\n");
        }
    if (Set)
	h += b;
}


/*-->SetString*/
/**********************************************************************/
/*****************************  SetString  ****************************/
/**********************************************************************/

void
SetString(firstch, PassNo)              /* read and set a consecutive string of chars */
int firstch, PassNo;
{
    char s[256];
    register char *sp;
    register int  c;
    register struct char_entry *ptr;
    int len, hhold;

    /* read entire string of chars */

    for(c = firstch, sp = s;  c >= SETC_000 && c <= SETC_127; ) {
        *sp++ = c;
        c = NoSignExtend(dvifp, 1);
        }
    fseek(dvifp, -1, 1);        /* backup one character */

    len = sp - s;               /* NULL's are valid chars, so cant use for string termination */

    /* ensure that all characters are loaded, */

    for(sp = s; sp < s+len; sp++) {
        ptr = &(fontptr->ch[*sp]);
        if( !(ptr->where.isloaded) )
                LoadAChar(*sp, ptr);
        }

    /* emit the instructions */

    if( PassNo == 0 ) return;
    SetPosn(h, v);
    if( fontptr->font_file_id != NOFILE ) {     /* ignore missing fonts */
        if( len <= 1 ) {
            EMITN(s[0]); 
            EMITS("c\n"); 
            }
        else {
            EMITC('(');
            for( sp=s;  sp < s+len;  sp++) {
                    if( *sp < ' ' || *sp >= 0177 )
                            EMITO(*sp);
                    else if( *sp == '(' || *sp == ')' || *sp == '\\') {
                            EMITC('\\'); 
                            EMITC(*sp); 
                            }
                    else
                            EMITC(*sp);
                    }
            EMITS(") s\n");
            }
        }

    /* compute updated positions */
    
    hhold = hh;
    for(sp = s; sp < s+len; sp++) {
        ptr = &(fontptr->ch[*sp]);
        h += ptr->tfmw;
        hh += ptr->tfmw;
        }
    if( fontptr->font_file_id == NOFILE ) hh = hhold;   /* because it didn't move */

#ifdef STATS
    Stnc += len;
    fontptr->ncts += len;
#endif
}


/*-->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;
	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");
    }
}
!Funky!Stuff!
echo x - dvi2ps.hlp
cat >dvi2ps.hlp <<'!Funky!Stuff!'
DVI2PS           UNIX Programmer's Manual            DVI2PS


NAME
     dvi2ps  - convert a DVI file to PostScript  (PostScript is a trademark
              of Adobe Systems, Inc).

SYNOPSIS

     dvi2ps [ -p ] [ -s ] [ -r ] [ -a pxldir ]  [-f n]  [-t n]  [-m n] dvifile[.dvi]


DESCRIPTION

     This program converts a DVI file to PostScript, and writes the result
     to standard output.  The result requires a small amount of PostScript
     source to precede it to the printer, before it can be successfully printed.

ARGUMENTS


     -p         - do not preload font information.
          Occasionally there may be insufficent memory to hold the
          information about all of the fonts in the system.  Portions
          of the document may be converted by including the -p option
          on the command line.  This will prevent the preloading of
          all fonts into the system and instead use demand loading of
          the font tables. 

     -s         - turn on printing of statistics.
          Some versions of dvi2ps will optionally print statistics about
          font usage and some other information that is generally only 
          interesting to developers.  On these systems, -s turns on
          the statistics printing.

     -r   - stack pages in reverse order.  
          Normally, the DVI pages are processed in reverse order, with the
          result that they are stacked in the correct order in the output
          tray.  This option reverses that.

     -a pxldir  - specify different area for PXL files.
          Specifying "-a pxldir" causes directory "pxldir" to be searched
          for all pxl files, instead of the default directory.

     -f n specify a starting page number (this is a TeX page number, \count0).

     -t n specify an ending page number.

     -m0 | -mh | -m1 | -m2 | -m3 | -m4
          specify a magstep to use to print the document.  This overrides
          whatever might be in the DVI file.

     -m n specify a magnification to use to print the document.  This should
          probably be one of the magic numbers 1000, 1095, 1200, 1440, 1728,
          but no checking is done.  Note: if your site does not have the
          complete set of 300 dpi fonts, this option might be disabled.

NOTES

     This is a `bare bones' DVI-to-PostScript program.  Minimal error
     checking is done.

     Not all fonts are available in the resolution needed to display on the 
     laser printer;  when a missing font is encountered, dvi2ps will continue 
     to process your dvi file, and and will log a warning message. Gaps will 
     appear in the document where the missing characters should have been.

     It can take up to 60 seconds for the first page to be output.  After a
     head of steam has been built up, it can roll along at 5-10 seconds
     per page.


FILES
     *.dvi                       TeX DeVice Independent output file

     /local/tex/pxl300/%.%pxl    TeX default font rasters
     /local/tex/tex.ps           PostScript support code.


SEE ALSO
     tex

BUGS
     Probably too numerous to mention.

     There is likely a limit to the size of documents that can be printed (at 
     least, on the Apple LaserWriter).  If you get VMerrors reported when 
     printing, use the '-f' and '-t' options, to select a range of pages.
     The exact limit is unknown, but is probably well in excess of 50 pages
     for "normal" documents, decreasing with number of different fonts used,
     size of fonts, etc.

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 then to produce PostScript.

Printed 1/7/85
!Funky!Stuff!
echo x - tex.ps
cat >tex.ps <<'!Funky!Stuff!'
%!
% a start (Ha!) at a TeX mode for PostScript
% Caution:  the following violates almost all codes of good programming practice

(Starting TeX job\n) print flush
                        
                        % units are in "dots" (300/inch)
/Resolution 300 def
/Page-X-Offset 250 def  % pages are shifted right this much for TeX
/Page-Y-Offset 275 def  % pages are shifted down this much for TeX
/Inch  {Resolution mul} def  % converts inches to internal units

/PageCounter statusdict begin pagecount end def  % so we can report # pages printed

/@newfont       % id @newfont -         -- initialize a new font dictionary
  { /newname exch def
    pop
    newname 7 dict def          % allocate new font dictionary
    newname load begin
        /FontType 3 def
        /FontMatrix [1 0 0 1 0 0] def
        /FontBBox [0 0 1 1] def
        /BitMaps 128 array def
        /BuildChar {CharBuilder} def
        /Encoding 128 array def
        0 1 127 {Encoding exch /.undef put} for
        end
    newname newname load definefont pop
  } def


% the following is the only character builder we need.  it looks up the
% char data in the BitMaps array, and paints the character if possible.
% char data  -- a bitmap descriptor -- is an array of length 6, of 
%          which the various slots are:

/ch-image {ch-data 0 get} def   % the hex string image
/ch-width {ch-data 1 get} def   % the number of pixels across
/ch-height {ch-data 2 get} def  % the number of pixels tall
/ch-xoff  {ch-data 3 get} def   % number of pixels below origin
/ch-yoff  {ch-data 4 get} def   % number of pixels to left of origin
/ch-tfmw  {ch-data 5 get} def   % spacing to next character

/CharBuilder    % fontdict ch Charbuilder -     -- image one character
  { /ch-code exch def           % save the char code
    /font-dict exch def         % and the font dict.
    /ch-data font-dict /BitMaps get ch-code get def     % get the bitmap descriptor for char
    ch-data null eq not
      { ch-tfmw   0   ch-xoff neg   ch-yoff neg   ch-width ch-xoff sub   ch-height ch-yoff sub
            setcachedevice
        ch-width ch-height true [1 0  0 1  ch-xoff ch-yoff]
            {ch-image} imagemask
      }
    if
  } def


/@sf            % fontdict @sf -        -- make that the current font
  { setfont
  } def

                % in the following, the font-cacheing mechanism requires that
                % a name unique in the particular font be generated

/@dc            % char-data ch @dc -    -- define a new character bitmap in current font
  { /ch-code exch def
    /ch-data exch def
    currentfont /BitMaps get ch-code ch-data put
    currentfont /Encoding get ch-code 
       dup (   ) cvs cvn   % generate a unique name simply from the character code
       put
  } def

/@bop0           % n @bop0 -              -- begin the char def section of a new page
  { (Page ) print == flush
  } def

/@bop1           % n @bop1 -              -- begin a brand new page
  { pop
    erasepage initgraphics
%                translations are a haque to get correct margins (1" default for TeX)
    [1.0 0.0 0.0 -1.0 Page-X-Offset 11 Inch Page-Y-Offset add]  setmatrix
    /SaveImage save def
  } def

/@eop           % - @eop -              -- end a page
  { showpage 
    SaveImage restore
%%    vmstatus exch sub == pop          % print a few statistics (mem remaining)
  } def

/@end           % - @end -              -- done the whole shebang
  { (Done! ) print 
    statusdict begin pagecount end PageCounter sub
    dup /PageCounter exch def
    (      ) cvs print
    ( pages printed.\n) print flush
    erasepage initgraphics
    count 0 gt             % print stats if stack not empty           
      { PageCounter 3 ge   % and if there were a significant number of pages
          { /Times-Bold findfont 16 scalefont setfont
            newpath 200 500 moveto
            count
              { gsave 
                  (                                                           ) cvs show
                grestore
                0 -30 rmoveto
              }
            repeat
            0 -20 rmoveto 
            PageCounter (      ) cvs show
            ( pages printed.) show
            0.3 setgray 
            newpath 0 792 moveto
            0 -24 rlineto 692 0 rlineto 0 24 rlineto closepath fill
            newpath 0 0 moveto
            692 0 rlineto 0 24 rlineto -692 0 rlineto closepath fill
            showpage
          }
        if
      }
    if
  } def

/p              % x y p -               -- move to position
  { moveto
  } def

/r              % x r -                 -- move right
  { 0 rmoveto
  } def

/s              % string s -            -- show the string
  { show
  } def

/c              % ch c -                -- show the character (code given)
  { c-string exch 0 exch put
    c-string show
  } def

/c-string ( ) def

/ru             % dx dy ru -   -- set a rule (rectangle)
  { /dy exch def
    /dx exch def
    /x currentpoint /y exch def def   % remember current point
    newpath x y moveto
    dx 0 rlineto
    0 dy rlineto
    dx neg 0 rlineto
    closepath fill
    x y moveto
  } def

% this will be invoked as the result of a \special command (for the
% inclusion of PostScript graphics).  The basic idea is to change all
% scaling and graphics back to defaults, but to shift the origin
% to the current position on the page.  Due to TeXnical difficulties,
% we only set the y-origin.  The x-origin is set at the left edge of
% the page.

/@beginspecial          % - @beginspecial -     -- enter special mode
  { /SpecialSave save def gsave
    currentpoint initgraphics 
       exch pop Page-Y-Offset sub         % remember, page is offset vertically
       72 1 Inch div mul                  % convert this dimension to points
       0 exch translate
  } def

/@endspecial            % - @endspecial -       -- leave specail mode
  { grestore SpecialSave restore
  } def
!Funky!Stuff!
-------