DataMuseum.dk

Presents historical artifacts from the history of:

DKUUG/EUUG Conference tapes

This is an automatic "excavation" of a thematic subset of
artifacts from Datamuseum.dk's BitArchive.

See our Wiki for more about DKUUG/EUUG Conference tapes

Excavated with: AutoArchaeologist - Free & Open Source Software.


top - metrics - download
Index: T U

⟦d97a2f457⟧ TextFile

    Length: 127800 (0x1f338)
    Types: TextFile
    Notes: Uncompressed file

Derivation

└─⟦52210d11f⟧ Bits:30007239 EUUGD2: TeX 3 1992-12
    └─⟦af5ba6c8e⟧ »unix3.0/DVIWARE.tar.Z« 
        └─⟦ca79c7339⟧ 
            └─⟦2c344d671⟧ »DVIware/obsolete/mitdrivers/dvi2ps.sh.Z« 
                └─⟦this⟧ 

TextFile

#	This is a shell archive.
#	Remove everything above and including the cut line.
#	Then run the rest of the file through sh.
#-----cut here-----cut here-----cut here-----cut here-----
#!/bin/sh
# shar:	Shell Archiver
#	Run the following text with /bin/sh to create:
#	Description
#	Makefile
#	README
#	applef.c
#	commands.h
#	dvi2ps.1
#	dvi2ps.c
#	dvi2ps.man
#	dvipsf.c
#	findfile.c
#	findfile.h
#	gf.c
# This archive created: Wed Jun 21 16:40:31 1989
echo shar: extracting Description '(3031 characters)'
cat << \SHAR_EOF > Description
Dvi2ps is the program to translate 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).

The current version is set to use gf format fonts at 300 dpi (gf is Generic
Font format as produced by METAFONT, and is a much tighter format than
the old loose-packed pxl format, which is now officially obsolete.)
The Makefile allows dvi2ps to be compiled for the use of pxl files, but
we strongly advise conversion to gf format. dvi2ps 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 
better speeds 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.  There is no effective way of converting
carefully rasterised fonts as produced by METAFONT into PostScript outlines,
but some thought is being given to rewriting the output end of METAFONT
to produce PostScript.

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.

-------> N.B. 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 are small anomalies.  However, care is taken,
     and the result is quite acceptable (at least to many untrained eyes).

In summary, it was quite easy to develop and will serve us well until 
something better comes along.

(This file last updated 8 September, 1986, by P. A. MacKay)
SHAR_EOF
if test 3031 -ne "`wc -c Description`"
then
echo shar: error transmitting Description '(should have been 3031 characters)'
fi
echo shar: extracting Makefile '(1022 characters)'
cat << \SHAR_EOF > Makefile
# The following file and directory specifications may need changing at
# your site:
#
# where are the bitmaps stored?
FONTAREA=/usr/lib/tex/fonts
#
# where is the header file to be found?
HDRFILE=/usr/lib/tex/tex.ps
#
# where is the software to be installed
BINAREA=/usr/local/bin
#
# an Apollo-specific spool file
SPOOLFILE=/usr/spool/laserwriter/apollo
#
#
# By default we will use GF format files.  If you want to use PXL
# format instead, then include a -DUSEPXL below.  Actually, if this
# is the case, the routines in gf.c are not needed
#
CFLAGS = -DFONTAREA=\"${FONTAREA}\" -DHDRFILE=\"${HDRFILE}\" \
         -DSPOOLFILE=\"${SPOOLFILE}\" -O

all: dvi2ps

dvi2ps:	dvi2ps.o findfile.o gf.o
	cc ${CFLAGS} -o dvi2ps dvi2ps.o findfile.o gf.o

install: all
	install -s -m 755 dvi2ps ${BINAREA}/dvi2ps
	cp tex.ps ${HDRFILE}

#
# The following may be useful if you are trying to run this as a
# printcap filter
#

applef:	applef.c
	${CC} -o applef ${CFLAGS} applef.c

dvipsf:	dvipsf.c
	${CC} -o dvipsf ${CFLAGS} dvipsf.c
SHAR_EOF
if test 1022 -ne "`wc -c Makefile`"
then
echo shar: error transmitting Makefile '(should have been 1022 characters)'
fi
echo shar: extracting README '(2498 characters)'
cat << \SHAR_EOF > README
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
	% lpr -Pps myfile.ps

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.


Installation comments:
======================

In installing this software, you will need to put tex.ps in
/usr/lib/tex/tex.ps.  If you want to put it somewhere else, see the
definition in the Makefile.  tex.ps is incorporated into the PostScript file
produced by dvi2ps.

The font area is assumed to be /usr/lib/tex/fonts.  I do not believe that
that this filter supports the TEXFONTS environment path.  The font area is
arranged in a new fashion that will probably be showing up in other device
drivers as well.  All the tfm files are contained in /usr/lib/tex/fonts.  If
a file named SUBDIR is present in /usr/lib/tex/fonts (or whatever directory
name you select), then the name of the font is taken as the name of a
subdirectory in searching for the pxl file associated with the font.  In
other words, cmr10.1500pxl will be found in
/usr/lib/tex/fonts/cmr10/cmr10.1500pxl.  When the file named SUBDIR is not
present, all pxl files are looked for in the directory itself, in other
words, /usr/lib/tex/fonts/cmr10.1500pxl in the above example.


printcap information
====================

MIT uses another program called dvipsf when the LaserWriter is used with the
/etc/printcap file.  dvipsf invokes dvi2ps and applef.  Both dvipsf.c and
applef.c are included here.  MIT's printcap entry for the laserwriter reads:
7th Floor LaserWriter|lw7|7lw|laserwriter|apple|LE-MONDE|LE-MONDE-LGP|LE-MONDE-ASCII|LE-MONDE-DVI:\
	:cP=LE-MONDE-LGP:cT:dP=LE-MONDE-DVI:dT:vP=LE-MONDE:\
	:br#9600:rw:fc#0000374:fs#0000003:xc#0:xs#0040040:mx#0:\
	:lp=/dev/ttyh5:sd=/usr/spool/lw7:pl#66:pw#89:\
	:lf=/usr/spool/lw7/log:of=/usr/lib/applef:\
	:md=/usr/spool/lw7/motd:vf=/usr/lib/applef:\
	:df=/usr/lib/dvipsf:cf=/usr/lib/applebitf:


History and acknowledgements
============================

The driver was converted by Neal Holtz of Carleton University from a Sun
previewer originally written by Mark Senn and later modified by others (see
dvi2ps for specifics).  Additional modifications and enhancements have been
done by Scott Jones and Chris Lindblad at MIT.

(These notes added by Richard Furuta)
SHAR_EOF
if test 2498 -ne "`wc -c README`"
then
echo shar: error transmitting README '(should have been 2498 characters)'
fi
echo shar: extracting applef.c '(8198 characters)'
cat << \SHAR_EOF > applef.c
/*
 *    applef.c - output filter for postscript to printer
 *              Also figures out if it should be an ascii filter
 *              instead, if a -l or -w swich is given.
 *
 *    Copyright 1985 Massachusetts Institute of Technology
 *    Author: CJL@OZ
 *
 *
 *    TODO:
 *    Page ordering so they will come out right using structuring
 *      conventions defined by adobe.
 *
 */

#include <stdio.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/stat.h>

#define MAXTFP    1000		/* Maximim # of pages in temp file */
#define MAXWAIT    900		/* Maximum time to wait for resync (sec) */
#define TOPY	   760
#define BOTTOMY     35
#define LEFTX       60
#define YINCR       11
#define MIN(a,b)    (((a) < (b))? (a):(b))
#define ALARM_TIME   5		/* Time between alarm signals (sec) */
#define PAPER_TIME 600		/* Time between paper out complaints (sec) */
#define STATUS_TIME 60		/* Time between printer status checks (sec) */

/* constants */
int infinity = 10000000;
char qsend[] = "/usr/local/bin/send";
char msg_tail[] = " ]%%\r\n";
char printer_error[] = "%%[ PrinterError: ";
char status_msg[] = "%%[ status: ";

/* variables */
int length = 66;
int width = 89;
long pprtim = 0;
long ststim = 0;
int ascii = 0;			/* Poscript filter by default */
char *user,*host;
int curry,charpos,nchars;
long tfpos[MAXTFP],tfp;
FILE *tf;
char tfn[256];
char logbuf[BUFSIZ],*logbp;
char last_status[BUFSIZ];

/* First, all the code for just sending chars to the printer */

int synched = 0;

timeout()
{
  long t;

  time(&t);
  alarm(ALARM_TIME);
  if (t - ststim > STATUS_TIME) {
    write(1,"\024",1); 		/* Control-T */
    ststim = t;
  }
  getlog();
}

getlog()
{
  register int i;
  int n;
  char buf[BUFSIZ],ch;

  while ((ioctl(1,FIONREAD,&n) >= 0) && n) {
    if (n > sizeof(buf)) n = sizeof(buf);
    n = read(1,buf,n);
    if (n > 0) {
      for (i=0; i<n; i++) {
	if ((ch = buf[i]) == 4) synched++;
	else {
	  *logbp++ = ch;
	  if ((ch == '\n') || (logbp >= logbuf+BUFSIZ)) flushlog();
	}
      }
    } else {
      perror("read from the printer");
      return;
    }
  }
  fflush(stderr);
}

dopaperout()
{
  char cmdline[256];
  FILE *f,*popen();
  long t;

  time(&t);
  if (t - pprtim > PAPER_TIME) {
    syslog(LOG_CRIT,"out of paper");
    if (user != NULL && host != NULL) {
      sprintf(cmdline,"exec %s %s@%s",qsend,user,host);
      if ((f = popen(cmdline,"w")) != NULL) {
	fprintf(f,"You need to add paper to the printer.");
	pclose(f);
      }
    }
    pprtim = t;
  }
}

dostatusmsg(msg)
     char *msg;
{
  if (strcmp(msg,last_status)) {
    syslog(LOG_WARNING,"status: %s",msg);
    strcpy(last_status,msg);
  }
  if (!strcmp(msg,"out of paper")) dopaperout();
}

doprintererror(msg)
     char *msg;
{
  syslog(LOG_WARNING,"printer error: %s",msg);
  if (!strcmp(msg,"out of paper")) dopaperout();
}

flushlog()
{
  register char *p;

  if ((logbp - logbuf > sizeof(printer_error)-1 + sizeof(msg_tail)-1) &&
      (!strncmp(logbuf,printer_error,sizeof(printer_error)-1))) {
    *(logbp-sizeof(msg_tail)+1) = 0;
    doprintererror(logbuf+sizeof(printer_error)-1);
  } else if ((logbp - logbuf > sizeof(status_msg)-1 + sizeof(msg_tail)-1) &&
	     (!strncmp(logbuf,status_msg,sizeof(status_msg)-1))) {
    *(logbp-sizeof(msg_tail)+1) = 0;
    dostatusmsg(logbuf+sizeof(status_msg)-1);
  } else for (p = logbuf; p < logbp; p++) {
    if (ascii || (tf == NULL)) putc(*p,stderr);
    else dochar(*p);
  }
  logbp = logbuf;
}

resync()
{
  int seconds = 0;
  struct stat *buf;

  fflush(stdout);
  fstat(stdout,buf);
  if (buf->st_mode&S_IFCHR){
    synched = 0;
    write(1,"\004",1);
    while (!synched && ((seconds += ALARM_TIME) < MAXWAIT)) pause();
    if (!synched) syslog(LOG_CRIT,"synchronization timeout");
  }
  flushlog();
}

init_printer()
{
  strcpy(last_status,"idle");
  logbp = logbuf;
  signal(SIGIO,getlog);
  signal(SIGALRM,timeout);
  fcntl(1,F_SETFL,FAPPEND|FASYNC);
  alarm(ALARM_TIME);

  resync();
  
  /* Open a temp file for sending the data 
   * for reversing the order of output
   */
  tf = fopen(mktemp(strcpy(tfn,"/usr/tmp/applef.XXXXXX")),"w+");
  if (tf == NULL) {
    perror(tfn);
    exit(1);
  }
  tfp = 0;
  unlink(tfn);
};

term_printer()
{
  resync();
  alarm(0);
};    

copychars(infd,outfd,nchars)
{
  register int i,j;
  register char *p;
  char buf[BUFSIZ];

  i = 0;
  while ((nchars > 0) &&
	 (i = read(infd,p = buf,MIN(sizeof(buf),nchars))) > 0) {
    nchars -= i;
    while (i > 0) {
      if ((j = write(outfd,p,i)) > 0) {
	i -= j;
	p += j;
      } else {
	perror("applef");
	i = 0;
      }
    }
  }
  if (i < 0) perror("applef");
}

main(argc, argv) 
    int argc;
    char *argv[];
{
  register int ch;
  int i;
  char *rindex();
  char lognam[256];

  if (rindex(argv[0],'/')) argv[0] = rindex(argv[0],'/')+1;
  for (i = 1; i < argc; i++) {
    if (argv[i][0] == '-') switch (argv[i][1]) {
    case 'h':
      host = argv[++i];
      break;

    case 'l':
      ascii++;			/* So I must be an ascii filter */
      sscanf(argv[i]+2,"%d",&length);
      break;

    case 'n':
      user = argv[++i];
      break;

    case 'w':
      ascii++;			/* So I must be an ascii filter */
      sscanf(argv[i]+2,"%d",&width);
      break;

    default:
      break;
    }
  }
  if (user != NULL) sprintf(lognam,"%s (%s@%s)",argv[0],user,host);
  else sprintf(lognam,"%s",argv[0]);
  openlog(lognam,LOG_PID);
  init_printer();
  starttext();
  if (ascii) {
    while (!ferror(stdin) && (ch = getchar()) != EOF) switch (ch) {
    case '\031':
      /*
       * lpd needs to use a different filter to
       * print data so stop what we are doing and
       * wait for lpd to restart us.
       */
      if ((ch = getchar()) == '\1') {
	resync();
	kill(getpid(), SIGSTOP);
	resync();
	break;
      } else {
	ungetc(ch, stdin);
	ch = '\031';
      }
    default:
      dochar(ch);
    }
    if (ferror(stdin)) perror("applef stdin");
  } else {
    copychars(0,1,infinity);
    resync();
  }
  endtext();
  term_printer();
  exit(0);
}
\f


/* Now code for converting text files to Postscript
 * and sending it to the printer. We need this stuff
 * to print printer responses after the print job,
 * and to print in ascii mode.
 */

starttext()
{
  newpage();
}

endtext()
{
  long end, curr;
  FILE *tempf;
  int tempfd;

  dochar('\f');
  tfpos[tfp] = ftell(tf);
  fflush(tf);
  tempf = tf;
  tf = NULL;
  tempfd = fileno(tempf);
  /* now send the pages to the printer in reverse order */
  while (--tfp >= 0) {
    curr = tfpos[tfp];
    end = tfpos[tfp + 1];
    lseek(tempfd,curr,0);
    copychars(tempfd,1,end-curr);
  };
  fclose(tempf);
}  

newpage()
{
  nchars = 0;
  charpos = 0;
  curry = TOPY;
}

pageinit()
{
  fflush(tf);
  if (tfp >= MAXTFP) {
    fprintf(stderr,"too many pages\n");
    exit(1);
  }
  tfpos[tfp++] = ftell(tf);
  fprintf(tf,"/Courier findfont 10 scalefont setfont\n"); /* font */
}

dostring(p)
char *p;
{
  register char ch;

  while (ch = *p++) dochar(ch);
}

dochar (ch)
int ch;
{
  register int i;

  if (ch < ' ') 
    switch (ch) {
    case '\b':
      if (charpos) { 
	fprintf(tf,") show\n");
	fprintf(tf,"(a) stringwidth pop neg 0 rmoveto\n");
	if (--charpos) fprintf(tf,"(");
      }
      break;

    case '\t':
      for (i = 8 - charpos%8; i > 0; i--) dochar(' ');
      break;

    case '\n':
      if (curry - YINCR < BOTTOMY) dochar('\f');
      else {
	if (charpos) fprintf(tf,") show\n");
	curry -= YINCR;
	charpos = 0;
      }
      break;

    case '\r':
      if (charpos) fprintf(tf,") show\n");
      charpos = 0;
      break;

    case '\f':
      if (charpos) fprintf(tf,") show ");
      if (nchars) fprintf(tf,"showpage\n");
      newpage();
      break;
    
    default:
      dochar('^'); dochar('\b'); dochar('|');
      dochar(ch+'A'-001);
      break;
    } else {
      if (!nchars++) pageinit();
      if (!charpos++) fprintf(tf,"%d %d moveto (",LEFTX,curry);
      if (charpos >= width) {
	putc('!',tf);
	dochar('\n');
	dochar(ch);
      } else switch (ch) {
      case '\\':
      case '/':
      case '(':
      case ')':
	putc('\\',tf);
    
      default:
	putc(ch,tf);
	break;
      }
    }
}
SHAR_EOF
if test 8198 -ne "`wc -c applef.c`"
then
echo shar: error transmitting applef.c '(should have been 8198 characters)'
fi
echo shar: extracting commands.h '(6168 characters)'
cat << \SHAR_EOF > commands.h
/*
 *
 * $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
SHAR_EOF
if test 6168 -ne "`wc -c commands.h`"
then
echo shar: error transmitting commands.h '(should have been 6168 characters)'
fi
echo shar: extracting dvi2ps.1 '(6839 characters)'
cat << \SHAR_EOF > dvi2ps.1
.TH DVI2PS 1L ""
.UC
.SH NAME
dvi2ps \- convert a DVI file to PostScript  
.br
(PostScript is a trademark of Adobe Systems, Inc).
.SH SYNOPSIS
.B dvi2ps
[
.B \-a 
pxldir
] [-c] [-d] [-f n] [-h] [-i file] [-m n] [-n n] [-o str] [-p] [-q] [-r] [-s] [-t n] dvifile[.dvi]
.br
.SH DESCRIPTION
.I dvi2ps
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.
(By default, that PostScript code is prepended to the output).
.TP
.B \-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.
.TP
.B \-c
Create an output file in the spool directory.
This is fairly Apollo-specific, and may be disabled at other
sites.  When given, the output is directed to a file with
a unique name, created in a spool directory.
.TP
.B \-d n
Specify device resolution.  Default is 300, a possible alternative
is 600 for the Varityper VT600.  Use of the -d 600 flag will
automatically call in the file tex6.ps in place of tex.ps.
The tex6.ps file ought to be in the same directory as tex.ps.
If dvi2ps was compiled with -DDEBUG, the -d flag will also
select debugging output (you probably don't want to).
.TP
.B \-f n
Specify a starting page number.
(this is a TeX page number -- \\count0).
.TP
.B \-h
Do not copy the standard header file.
This option prevents the standard PostScript header file being
prepended to the output.
.TP
.B \-i file
Copy the named file to the output
The contents of the file named will be copied to the output
after the standard header file has been copied.
.TP
.B  \-m0 "| -mh | -m1 | -m2 | -m3 | -m4"
Specify a magstep to use to print the document.  This overrides
whatever might be in the DVI file.
.TP
.B \-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.
.TP
.B \-n n
Specify the number of copies to print
.TP
.B \-o str
Specify an printing option.
valid options are "letter", "note", "legal", "landscape" and
"manualfeed" (without the quotes).  This argument may be repeated 
several times.
.TP
.B \-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. 
.TP
.B \-q
Be quiet.  Don't chatter about pages converted, etc.
.TP
.B \-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.
.TP
.B \-s
Turn on printing of statistics.
Some versions of 
.I 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.
.TP
.B \-t n 
Specify an ending page number.
.TP
.B \-w
Don't print out warnings.
.SH NOTES
This is a `bare bones' DVI-to-PostScript program.  Minimal error
checking is done.
.PP
Not all fonts are available in the resolution needed to display on the 
laser printer;  when a missing font is encountered, 
.I 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.
.pp
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.
.SH TeX \\\\special command:
This program supports use of the "\\special" command in TeX to include
special PostScript code for graphics, etc.  Specifying
"\\special{psfile=foo.ps}" in the TeX source will result in the contents
of file "foo.ps" (assumed to contain PostScript code) being copied 
into the output at that point.  For most included graphics, the
users (0,0) point will be set to the point of the \\special command
with x and y coordinates increasing up and to the right and in units
of PostScript points (72/inch) -- thus you must explicitly leave space
above the \\special command for most graphics.  For graphics produced by 
Apple Macintoshes (i.e., MacDraw, MacPaint, etc.), the top left corner of 
the drawing will be at the point of the \\special command; in this case you
must leave the required space below the \\special.
.PP
The \\special string can contain any number of the following 
"keyword=value" pairs, seperated by blanks:

   Keyword   Value Type
   -------   ----------
   psfile    string      - A PostScript file to include
   hsize     dimension   - Maximum horizontal size
						(for clipping)
   vsize     dimension   - Maximum vertical size
						(for clipping)
   hoffset   dimension   - Amount to shift right
   voffset   dimension   - Amount to shift up
						(or down, for MacDrwgs)
   hscale    number      - A scale factor in x-dimension
   vscale    number      - A scale factor in y-dimension
.PP
dimensions are given in inches.
.PP
THUS: \\special{psfile=foo.ps hoffset=1 hscale=0.9 vscale=0.9}
will shift the graphics produced by file "foo.ps" right by
1", and will draw it at 0.9 normal size.
.PP
hsize and vsize are given relative to the (0,0) point of the drwg
and are unaffected by offsets and scales.
.PP
offsets are given relative to the point of the \\special command,
and are unaffected by scales.
.PP
If Macintosh drawings are to be included, the proper laserprep file
must be downloaded to the printer, either permanently or as another
header file in addition to the standard "tex.ps" header file.
.SH FILES
*.dvi             TeX DeVice Independent output file
/local/tex/pxl300/%.%pxl    TeX default font rasters
/local/lib/ps/tex.ps        PostScript support code.
.SH SEE ALSO
tex(1L)
.SH BUGS
Probably too numerous to mention.
.PP
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.
.SH 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.
SHAR_EOF
if test 6839 -ne "`wc -c dvi2ps.1`"
then
echo shar: error transmitting dvi2ps.1 '(should have been 6839 characters)'
fi
echo shar: extracting dvi2ps.c '(72283 characters)'
cat << \SHAR_EOF > dvi2ps.c
#define VERSION "2.10gf"

/*
 *
 * 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.
 *     Howard Trickey made it read GF files instead of PXL ones.
 *
 */

/* 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)
 *  7-Jun-86 (hwt) -- use gf files ("pxl" survives in variable names)
 *  8-Aug-86 (rkf) -- merged together the pxl and the gf versions.  Define
 *                    USEPXL should you want PXL files---gf is the default
 * 22-Dec-87 (pam) -- suppress (but do not remove) the function of the -d
 *		      flag for debugging, so that it can be used to specify
 *		      print-engine resolution (inspired by the VariTyper 600).
 *  5-Jan-88 (pam) -- provide for 256 character gf fonts.
 */


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

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


typedef int BOOLEAN;
#define NEW(A) ((A *) malloc(sizeof(A)))
/* #define DEBUG (use CFLAG instead) */ /* for massive printing of input */
					/* trace information; select by -d */
					/* option after filename: */
					/* dviview filename -d */
					/* we want to use -d for the resolution */
#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 can leave USEGLOBALMAG undefined when we have a limited
   number of font magnifications (at 300dpi) available.  Otherwise, we
   will simply complain about missing PXL files
 */

/* #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  TRUE             1
#define  FALSE            0
#define  FIRSTFNTCHAR     0
#ifdef USEPXL
#define  LASTFNTCHAR    127
#else
#define  LASTFNTCHAR    255
#endif

#ifndef FONTAREA
#define  FONTAREA         "/usr/lib/tex/fonts"
#endif

#ifndef HDRFILE
#define HDRFILE         "/usr/lib/tex.ps"
#endif

#ifdef apollo
#ifndef SPOOLFILE
#define SPOOLFILE       "/local/spool/laser/tex."
#endif
#define MAXFLEN 28
#endif apollo

#ifdef apollo
#define  MAXOPEN         45  /* limit on number of open font raster files */
#else !apollo
#define  MAXOPEN         12  /* limit on number of open font raster files */
#endif

#ifdef USEPXL
#define  NFNTCHARS      128
#else
#define  NFNTCHARS      256
#endif
#define  PXLID         1001
#define  READ             4  /* for access() */
				/* make resolution a switch option */
#define  DEFAULTRESOLUTION 300 /* can be changed with [-d integer] */
#define  DEFAULThconvRES 300 /* usually the same, but you can get */
#define  DEFAULTvconvRES 300 /* interesting effects if they are not */
			     /* should be yet another switch option (?) */
#define  STACKSIZE      100
#define  STRSIZE        257
#define  NONEXISTENT     -1   /* offset for PXL files not found */
#define  NO_FILE        (FILE *)-1

#ifdef apollo           /* define for enabling of -c option (create output file) */
#define CREOPT
#endif apollo

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

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

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

#ifndef USEPXL
/* interface to gf.c */
extern FILE *gfin;
extern int checksum;
extern long tfm_wd[], char_pointer[];
extern char char_exists[];
extern int num_cols, num_rows, num_bytes, x_offset, y_offset;
extern unsigned char bits[];
extern int gettochar();
extern void readbits();
extern void readpost();
extern void seekpost();
extern int seekchar();
#endif

#define EQ(a,b) (strcmp(a,b)==0)

                        /* output a formatted string */
#define EMIT      fprintf
                        /* output a simple string */
#define EMITS(s)  fputs(s,outfp)
                        /* 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)  putc(*(digit+((h>>4)&0xF)),outfp),\
                  putc(*(digit+(h&0xF)),outfp)
                        /* output a single character */
#define EMITC(c)  putc(c,outfp)
                        /* 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();
int     ChkOpt();               /* Check PostScript option for validity */
void    CopyFile();
void    DecodeArgs();
void    DoSpecial();
void    EmitChar();
void	Fatal();
void	FindPostAmblePtr();
void	GetBytes();
void	GetFontDef();
char   *GetKeyStr();
int     GetKeyVal();
int     HasBeenRead();
int     IsSame();
void    lcase();
void	MoveDown();
void	MoveOver();
int     NoSignExtend();         /* see cautionary note in code, re arithmetic vs logical shifts */
void	OpenFontFile();
#ifdef CREOPT
FILE*   OpenOutput();
#endif CREOPT
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 */
#ifdef USEPXL
   unsigned short width, height;/* width and height in pixels */
   short xOffset, yOffset;      /* x offset and y offset in pixels */
#endif
   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 (NO_FILE if none)         */
#ifdef USEPXL
   int magnification;	/* magnification read from PXL file         */
   int designsize;	/* design size read from PXL file           */
#endif
   struct char_entry ch[NFNTCHARS];/* 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   FontDensity = DEFAULTRESOLUTION; /* the usual Canon 300 dpi	*/
int   hconvResolution = DEFAULThconvRES; /* likewise */
int   vconvResolution = DEFAULTvconvRES;

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

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 */
char *Ifile[100];                       /* files to include */
int   v;				/* current vertical position                */
int   vv = 0;                           /* current v on device */
int   mag;			/* magnification specified in preamble      */
int   ncopies = 1;              /* number of copies to print                */
int   ndone = 0;                /* number of pages converted */
int   nif = 0;                  /* number of files to include */
int   nopen;			/* number of open PXL files                 */
int   nps = 0;                  /* number of PostScript commands to send    */
int   num;			/* numerator specified in preamble          */
#ifdef CREOPT
char  outfname[256];            /* name of output file                      */
#endif CREOPT
FILE  *outfp = NULL;            /* output file                              */
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		     */
char *PScmd[100];               /* PostScript commands to send              */
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 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);
    }

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

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

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

	    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(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;
	    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==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) {
        fprintf( stderr, "Total chars   diff chars   pxl bytes\n" );
        fprintf( stderr, "      #   %%        #   %%       #   %%\n" );
        fprintf( stderr, "------- ---   ------ ---   ----- ---\n" );
        for( p=hfontptr; p!=NULL; p=p->next ) {
                fprintf( stderr, "%7d%4d", p->ncts, (100*p->ncts + Stnc/2)/Stnc );
                fprintf( stderr, "%9d%4d", p->ncdl, (100*p->ncdl + Sndc/2)/Sndc );
                fprintf( stderr, "%8d%4d", p->nbpxl, (100*p->nbpxl + Snbpxl/2)/Snbpxl );
                fprintf( stderr, "  %s\n", p->psname );
                }
        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);
}


/*-->ChkOpt*/   /* check a user supplied option for validity */
/*********************************************************************/
/****************************** ChkOpt *******************************/
/*********************************************************************/

#define ISOPT(s) if( EQ(str,s) ) return( TRUE )

int
ChkOpt( str )
char    *str;
{
/*        lcase(str);  doesn't work */

        ISOPT("note");          /* its a shame to build this into the program */
        ISOPT("letter");
        ISOPT("legal");
        ISOPT("landscape");
        ISOPT("manualfeed");
        return( FALSE );
}


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

                case 'a':       /* a selects different pxl font area */
                    PXLpath = argv[++argind];
                    break;
#ifdef CREOPT
                case 'c':       /* create an output file in spool area */
                    G_create = TRUE;
                    break;
#endif CREOPT
		case 'd':	/* d selects font pixel density */
#ifdef DEBUG
		    Debug = TRUE;	/* and maybe Debug output too */
#endif
                    if( ++argind >= argc || sscanf(argv[argind], "%d", &FontDensity) != 1 )
                        Fatal("Argument is not a valid integer\n", 0);
		    hconvResolution = FontDensity;
		    vconvResolution = FontDensity;
                    Ifile[nif++] = "/usr/local/lib/tex/tex6.ps";
                    G_header = FALSE;
                    G_quiet = FALSE;
		    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 '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( 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;
                    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;

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


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

typedef enum {None, String, Integer, Number, Dimension} ValTyp;

typedef struct {
        char    *Key;           /* the keyword string */
        char    *Val;           /* the value string */
        ValTyp  vt;             /* the value type */
        union {                 /* the decoded value */
            int  i;
            float n;
            } v;
        } KeyWord;

typedef struct {
        char    *Entry;
        ValTyp  Type;
        } KeyDesc;

#define PSFILE 0
KeyDesc KeyTab[] = {{"psfile", String},
                    {"hsize", Dimension},
                    {"vsize", Dimension},
                    {"hoffset", Dimension},
                    {"voffset", Dimension},
                    {"hscale", Number},
                    {"vscale", Number}};

#define NKEYS (sizeof(KeyTab)/sizeof(KeyTab[0]))

void
DoSpecial( str, n )          /* interpret a \special command, made up of keyword=value pairs */
char    *str;
int n;
{ 
        char spbuf[STRSIZE]; 
        char *sf = NULL;
        KeyWord k;
        int i;

        str[n] = '\0';
        spbuf[0] = '\0';

        SetPosn(h, v);
        EMITS("@beginspecial\n");

        while( (str=GetKeyStr(str,&k)) != NULL ) {      /* get all keyword-value pairs */
                              /* for compatibility, single words are taken as file names */
                if( k.vt == None && access(k.Key,0) == 0) {
                        if( sf ) Warning("  More than one \\special file name given. %s ignored", sf );
                        strcpy(spbuf, k.Key);
                        sf = spbuf;
                        }
                else if( GetKeyVal( &k, KeyTab, NKEYS, &i ) && i != -1 ) {
                        if( i == PSFILE ) {
                                if( sf ) Warning("  More than one \\special file name given. %s ignored", sf );
                                strcpy(spbuf, k.Val);
                                sf = spbuf;
                                }
                        else            /* the keywords are simply output as PS procedure calls */
                                EMIT(outfp, "%f @%s\n", k.v.n, KeyTab[i].Entry);
                        }
                else Warning("  Invalid keyword or value in \\special - \"%s\" ignored", k.Key );
                }

        EMITS("@setspecial\n");

        if( sf )
                CopyFile( sf );
        else
                Warning("  No special file name provided.");

        EMITS("@endspecial\n");
}


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

#ifndef USEPXL
/* assume we just called readbits() */
#endif

void
EmitChar(c, ce)              /* output a character bitmap */
int c;
struct char_entry *ce;
{
#ifdef USEPXL
        int i;
        register int j;
#endif
        register unsigned char *sl;
#ifdef USEPXL
        register int cc;
        int nbpl, nwpl;
#else
        register int cc, i;
        int nbpl;
#endif
        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(outfp,"[ %d ] /%s @newfont\n", fontptr->font_mag, fontptr->psname );
 
        if( fontptr != prevfont ) {   /* because this isn't done on pass 0 */
                EMIT(outfp,"%s @sf\n", fontptr->psname);
                prevfont = fontptr;
                }
        EMITS("[<");
        cc = 2;
#ifdef USEPXL
        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;
                        }
#else
        nbpl = (num_cols + 7) >> 3;
        for(i=0, sl=bits; i<num_bytes; i++, sl++) {
                if( cc > 100 ) { EMITS("\n  ");   cc = 2; }
                EMITH(*sl);
                cc += 2;
#endif
                }
        cw = (float)ce->tfmw / (float)hconv;
        EMIT(outfp,"> %d %d %d %d %.3f] %d @dc\n", 
#ifdef USEPXL
             nbpl<<3, ce->height, ce->xOffset, (((int)ce->height)-ce->yOffset)-1, cw,
             c);
#else
             nbpl<<3, num_rows, x_offset, y_offset, cw, c);
#endif
        fontptr->ncdl += 1;

#ifdef STATS
#ifdef USEPXL
        Snbpxl += nbpl*ce->height;
        fontptr->nbpxl += nbpl*ce->height;
        Sonbpx += (ce->width*ce->height + 7) >> 3;
#else
        Snbpxl += nbpl*num_rows;
        fontptr->nbpxl += nbpl*num_rows;
        Sonbpx += (num_cols*num_rows + 7) >> 3;
#endif
        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");
#ifdef CREOPT
    if (G_create && outfp != NULL) {
        fclose(outfp);
        unlink(outfname);
        }
#endif CREOPT
    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");
}


/*-->GetKeyStr*/
/**********************************************************************/
/*****************************  GetKeyStr  ****************************/
/**********************************************************************/

        /* extract first keyword-value pair from string (value part may be null)
         * return pointer to remainder of string
         * return NULL if none found
         */

char    KeyStr[STRSIZE];
char    ValStr[STRSIZE];

char *GetKeyStr( str, kw )
char    *str;
KeyWord *kw;
{
        char *s, *k, *v, t;

        if( !str ) return( NULL );

        for( s=str; *s == ' '; s++ ) ;                  /* skip over blanks */
        if( *s == '\0' ) return( NULL );

        for( k=KeyStr;                          /* extract keyword portion */
             *s != ' ' && *s != '\0' && *s != '='; 
             *k++ = *s++ ) ;
        *k = '\0';
        kw->Key = KeyStr;
        kw->Val = v = NULL;
        kw->vt = None;

        for( ; *s == ' '; s++ ) ;                       /* skip over blanks */
        if( *s != '=' )                         /* look for "=" */
                return( s );

        for( s++ ; *s == ' '; s++ ) ;                   /* skip over blanks */
        if( *s == '\'' || *s == '\"' )          /* get string delimiter */
                t = *s++;
        else
                t = ' ';
        for( v=ValStr;                          /* copy value portion up to delim */
             *s != t && *s != '\0';
             *v++ = *s++ ) ;
        if( t != ' ' && *s == t ) s++;
        *v = '\0';
        kw->Val = ValStr;
        kw->vt = String;

        return( s );
}


/*-->GetKeyVal*/
/**********************************************************************/
/*****************************  GetKeyVal  ****************************/
/**********************************************************************/

        /* get next keyword-value pair
         * decode value according to table entry
         */

int GetKeyVal( kw, tab, nt, tno)
KeyWord *kw; 
KeyDesc tab[];
int     nt;
int     *tno;
{
        int i;
        char c = '\0';

        *tno = -1;

        for(i=0; i<nt; i++)
                if( IsSame(kw->Key, tab[i].Entry) ) {
                        *tno = i;
                        switch( tab[i].Type ) {
                                case None: 
                                        if( kw->vt != None ) return( FALSE );
                                        break;
                                case String:
                                        if( kw->vt != String ) return( FALSE );
                                        break;
                                case Integer:
                                        if( kw->vt != String ) return( FALSE );
                                        if( sscanf(kw->Val,"%d%c", &(kw->v.i), &c) != 1
                                            || c != '\0' ) return( FALSE );
                                        break;
                                case Number:
                                case Dimension:
                                        if( kw->vt != String ) return( FALSE );
                                        if( sscanf(kw->Val,"%f%c", &(kw->v.n), &c) != 1
                                            || c != '\0' ) return( FALSE );
                                        break;
                                }
                        kw->vt = tab[i].Type;
                        return( TRUE );
                        }

        return( TRUE );
}


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


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


/*-->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) != NO_FILE )
	        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 != NO_FILE) {
                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
                        }
 	        fclose( fid );
                }
	    current = least_used;
        }
        if ((pxlfp=BINARYOPEN(fontptr->name,"r")) == NULL) {
	    Warning("PXL file %s could not be opened",fontptr->name);
            pxlfp = NO_FILE;
            }
        else {
#ifdef STATS
            if (Stats) 
                fprintf(stderr, "PXL file %s opened.\n", fontptr->name);
#endif
            }
	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 */
#ifndef USEPXL
    gfin = pxlfp;			/* used in gf reader */
#endif
}

#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 += 1;
                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

/*-->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];
    int cmag;
    int nmag;
    char nname[NFNTCHARS];

    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
#ifdef USEPXL
			(float)FontDensity * 5.0) + 0.5);
#else
			(float)FontDensity) + 0.5);
#endif

    if (!findfile(&PXLpath,1,"",tfontptr->n,tfontptr->font_mag,tfontptr->name,
		  nname, &nmag))
      Fatal("no font %s.%d",tfontptr->n,mag);
      
    sprintf(tfontptr->psname, "%s.%d", tfontptr->n, tfontptr->font_mag);
    if (tfontptr != pfontptr)
	OpenFontFile();
#ifdef USEPXL
    if ( pxlfp == NO_FILE ) {                /* allow missing pxl files */
        tfontptr->magnification = 0;
        tfontptr->designsize = 0;
        for (i = FIRSTFNTCHAR; i <= LASTFNTCHAR; i++) {
#else
    for (i = FIRSTFNTCHAR; i <= LASTFNTCHAR; i++) {
#endif
	    tcharptr = &(tfontptr->ch[i]);
#ifdef USEPXL
	    tcharptr->width = 0;
	    tcharptr->height = 0;
	    tcharptr->xOffset= 0;
	    tcharptr->yOffset = 0;
#endif
	    tcharptr->where.isloaded = FALSE;
	    tcharptr->where.address.fileOffset = NONEXISTENT;
	    tcharptr->tfmw = 0;
            }
#ifdef USEPXL
        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 = FIRSTFNTCHAR; i <= LASTFNTCHAR; 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);
#else
    if ( pxlfp == NO_FILE )                /* allow missing pxl files */
        return;

    gfin = pxlfp;
    seekpost();
    readpost();
    if ((tfontptr->c != 0) && (checksum != 0) && (tfontptr->c != checksum))
	Warning("font = \"%s\",\n-->font checksum = %d,\n-->dvi checksum = %d",
	        tfontptr->name, tfontptr->c, checksum);

    for(i=FIRSTFNTCHAR; i<=LASTFNTCHAR; i++) {
	if (char_exists[i]) {
	    tcharptr = &(tfontptr->ch[i]);
	    tcharptr->tfmw = ((float)tfm_wd[i]*(float)tfontptr->s) /
	        (float)(1<<20);
	    tcharptr->where.address.fileOffset = char_pointer[i];
	}
#endif
    }
}


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


/*-->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 == NONEXISTENT) {
	ptr->where.address.pixptr = NULL;
        ptr->where.isloaded = TRUE;
	return;
        }

    OpenFontFile();
#ifdef USEPXL
    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;
#else
    fseek(gfin, ptr->where.address.fileOffset, 0);
    gettochar();
    readbits();
#endif
    ptr->where.isloaded = TRUE;

    EmitChar(c, ptr);
#ifdef USEPXL
        /* 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 */
#endif
}

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 != NO_FILE) {      /* 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 != NO_FILE) ) 
        EMIT(outfp,"%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
            EMITN(rx=PixRound(x,hconv));
            EMITN(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
}


/*-->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 != NO_FILE ) {     /* 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 == NO_FILE ) 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;
                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");
    }
}


#ifndef USEPXL
void bad_gf(n)
	int n;
{
	Fatal("Bad gf file, case %d\n",n);	/* See gf.c */
}
#endif
SHAR_EOF
if test 72283 -ne "`wc -c dvi2ps.c`"
then
echo shar: error transmitting dvi2ps.c '(should have been 72283 characters)'
fi
echo shar: extracting dvi2ps.man '(7822 characters)'
cat << \SHAR_EOF > dvi2ps.man
DVI2PS           **** Programmer's Manual            DVI2PS


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

SYNOPSIS

     dvi2ps [-a pxldir] [-c] [-d n] [-f n] [-h] [-i file] [-m n] [-n n] 
            [-o str] [-p] [-q] [-r] [-s] [-t 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.
     (By default, that PostScript code is prepended to the output).

ARGUMENTS


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

     -c         - create an output file in the spool directory.
          This is fairly Apollo-specific, and may be disabled at other
          sites.  When given, the output is directed to a file with
          a unique name, created in a spool directory.

     -d n       - select resolution (300 dpi is default, 600 is possible.)
          Use of the flag value -d 600 brings in the header file tex6.ps
          Also select debugging output if program was compiled with -DDEBUG.

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

     -h         - do not copy the standard header file.
          This option prevents the standard PostScript header file being
          prepended to the output.

     -i file    - copy the named file to the output
          The contents of the file named will be copied to the output
          after the standard header file has been copied.

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

     -n n       - specify the number of copies to print

     -o str     - specify an printing option.
          valid options are "letter", "note", "legal", "landscape" and
          "manualfeed" (without the quotes).  This argument may be repeated 
          several times.

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

     -q         - be quiet.
          Don't chatter about pages converted, etc.
         
     -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.

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

     -t n specify an ending page number.

     -w   Don't print out warnings.

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.

     TeX "\special" command:
     -----------------------

     This program supports use of the "\special" command in TeX to include
     special PostScript code for graphics, etc.  Specifying
     "\special{psfile=foo.ps}" in the TeX source will result in the contents
     of file "foo.ps" (assumed to contain PostScript code) being copied 
     into the output at that point.  For most included graphics, the
     users (0,0) point will be set to the point of the \special command
     with x and y coordinates increasing up and to the right and in units
     of PostScript points (72/inch) -- thus you must explicitly leave space
     above the \special command for most graphics.  For graphics produced by 
     Apple Macintoshes (i.e., MacDraw, MacPaint, etc.), the top left corner of 
     the drawing will be at the point of the \special command; in this case you 
     must leave the required space below the \special.

     The \special string can contain any number of the following 
     "keyword=value" pairs, seperated by blanks:

        Keyword         Value Type
        -------         ----------
        psfile          string          - specifies a PostScript file to include
        hsize           dimension       - specifies maximum horizontal size (for clipping)
        vsize           dimension       - specifies maximum vertical size (for clipping)
        hoffset         dimension       - specifies amount to shift right
        voffset         dimension       - specifies amount to shift up (or down, for MacDrwgs)
        hscale          number          - specifies a scale factor in x-dimension
        vscale          number          - specifies a scale factor in y-dimension

                        dimensions are given in PostScript points (72 per inch).

     THUS:  \special{psfile=foo.ps hoffset=72 hscale=0.9 vscale=0.9}

            will shift the graphics produced by file "foo.ps" right by
            1", and will draw it at 0.9 normal size.

      hsize and vsize are given relative to the (0,0) point of the drwg
      and are unaffected by offsets and scales.

      offsets are given relative to the point of the \special command,
      and are unaffected by scales.

      If Macintosh drawings are to be included, the proper laserprep file
      must be downloaded to the printer, either permanently or as another
      header file in addition to the standard "tex.ps" header file.



FILES
     *.dvi                       TeX DeVice Independent output file

     /local/tex/pxl300/%.%pxl    TeX default font rasters
     /local/lib/ps/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.

     If the Mac LaserPrep file has been loaded, offsets, sizes and scales
     in \special{} will not work properly for non-Macintosh graphics (don't ask).

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 9/21/85


SHAR_EOF
if test 7822 -ne "`wc -c dvi2ps.man`"
then
echo shar: error transmitting dvi2ps.man '(should have been 7822 characters)'
fi
echo shar: extracting dvipsf.c '(2718 characters)'
cat << \SHAR_EOF > dvipsf.c
/*
 *    dvipsf.c - output filter for postscript to printer
 *      uses these other programs:
 *        /usr/lib/postf   (the lpr filter for postscript to laserwriter)
 *        /usr/local/bin/dvi2ps (dvi to postscript translator)
 *        /usr/lib/tex.ps  (the postscript prologue to support TeX)
 *
 *    Copyright 1985 Massachusetts Institute of Technology
 *    Author: CJL@OZ
 *
 */

/* #define DEBUGGING */

#include <stdio.h>
#include <signal.h>
#include <sys/ioctl.h>
#include <fcntl.h>

#define PROLOGUE   "/usr/lib/tex.ps"
#define DVI2PS     "/usr/local/bin/dvi2ps -q"
#define CAT        "/bin/cat"
#define POSTF      "/usr/lib/applef"
#define TEXTF      "/usr/lib/applef"

FILE *popen();
char *user,*host;

main(argc, argv) 
    int argc;
    char *argv[];
{
  char tfn[BUFSIZ],cmdbuf[BUFSIZ],efn[BUFSIZ];
  register int ch;
  register FILE *tf;
  int olderrfd,i;
  char *rindex();
  FILE *ef,*of;

  if (rindex(argv[0],'/')) argv[0] = rindex(argv[0],'/')+1;
  for (i = 1; i < argc; i++) {
    if (argv[i][0] == '-') switch (argv[i][1]) {
    case 'h':
      host = argv[++i];
      break;

    case 'n':
      user = argv[++i];
      break;

    default:
      break;
    }
  }
  /* Copy the dvi data to a temp file, since we have to give it by name
   * to dvi2ps.
   */
  if ((tf = fopen(mktemp(strcpy(tfn,"/usr/tmp/dvipsf.XXXXXX")),"w"))
      == NULL) {
    perror(tfn);
    exit(2);
  }
  while (!ferror(stdin) && (ch = getchar()) != EOF) putc(ch,tf);
  fclose(tf);
  if (ferror(stdin)) {
    perror("dvipsf stdin");
    unlink(tfn);
    exit(2);
  }

  /* Now divert standard error to a temp file so we can print it later. */
  if ((ef = fopen(mktemp(strcpy(efn,"/usr/tmp/dvipsf.err.XXXXXX")),"w+"))
      == NULL) {
    perror(efn);
    unlink(tfn);
    exit(2);
  }
  unlink(efn);
  fflush(stderr); olderrfd = dup(2); close(2);
  dup(fileno(ef));

  /* Run the filters */
  if (user != NULL && host != NULL) 
    sprintf(cmdbuf,"%s %s | %s -n %s -h %s",DVI2PS,tfn,POSTF,user,host);
  else
    sprintf(cmdbuf,"%s %s | %s", DVI2PS, tfn, POSTF);
  system(cmdbuf);
  unlink(tfn);

  /* Now put back the old stderr */
  fflush(stderr); close(2); dup(olderrfd); close(olderrfd);

  /* And send all the messages to the printer */
  if (user != NULL && host != NULL) 
    sprintf(cmdbuf,"%s -w80 -l66 -n %s -h %s",TEXTF,user,host);
  else
    sprintf(cmdbuf,"%s -w80 -l66", TEXTF);
  if ((of = popen(cmdbuf,"w")) == NULL) {
    perror(TEXTF);
    exit(2);
  }
  rewind(ef);
  while (!ferror(ef) && (ch = getc(ef)) != EOF) if (ch != '\031') {
    putc(ch,of);
#ifdef DEBUGGING
    putc(ch,stderr);
#endif
  }
  fclose(ef); pclose(of);
  if (ferror(ef)) {
    perror(efn);
    exit(2);
  }
  
  exit(0);
}
SHAR_EOF
if test 2718 -ne "`wc -c dvipsf.c`"
then
echo shar: error transmitting dvipsf.c '(should have been 2718 characters)'
fi
echo shar: extracting findfile.c '(5047 characters)'
cat << \SHAR_EOF > findfile.c
/* findfile.c
 * Copyright 1985 Massachusetts Institute of Technology
 */

#include <stdio.h>
#include <sys/types.h>
#include <sys/dir.h>
#include "findfile.h"

#ifdef USEPXL
#define  NFNTCHARS      128
#else
#define  NFNTCHARS      256
#endif
 
int
findfileindir(area, name, mag, s, nname, nmag)
     char *area,*name,*s,*nname;
     int mag,*nmag;
{
  FILE *f;
  char buf[BUFSIZ];
  int found = 0;
    
  sprintf(s,"%s/SUBDIR",area);
#ifdef USEPXL
if (!access(s,0)) sprintf(s,"%s/%s/%s.%dpxl",area,name,name,mag);
else sprintf(s,"%s/%s.%dpxl",area,name,mag);
#else
  if (!access(s,0)) sprintf(s,"%s/%s/%s.%dgf",area,name,name,mag);
  else sprintf(s,"%s/%s.%dgf",area,name,mag);
#endif
  if (!access(s,4)) {
    strcpy(nname,name);
    *nmag = mag;
    return(-1);
  } else {
    sprintf(buf,"%s/NEEDED",area);
    if (!access(buf,2)) {
#ifdef USEPXL
      sprintf(s,"%s.%dpxl\n",name,mag);
#else
      sprintf(s,"%s.%dgf\n",name,mag);
#endif
      f = fopen(buf,"r+");
      while (fgets(buf,sizeof(buf),f)) if (!strcmp(buf,s)) found++;
      if (!found) fputs(s,f);
      fclose(f);
    }
    return(0);
  }
}


/* true if it found a file, false otherwise; name is in s */
int findfile(dirvec,dirveclen,area, name, mag, s, nname, nmag)
     char *dirvec[],*area,*name,*s,*nname;
     int dirveclen,mag,*nmag;
{
  int i,point;
  char family[NFNTCHARS];

  strcpy(nname,name);
  *nmag = mag;
  point = -1;
  (void) sscanf(name,"%[^0123456789.]%d",family,&point);

  /* First check dir area given in DVI file */
  if (*area && findfileindir(area, name, mag, s, nname, nmag)) return(-1);
  
  /* Then check along dirvec */
  for (i = 0; i < dirveclen; i++) 
    if (findfileindir(dirvec[i], name, mag, s, nname, nmag)) return(-1);

  /* next check for closest magnification along dirvec */
  return(findanyfile(dirvec,dirveclen,family,point,mag,name,s,nname,nmag));
}
  
int strdiff(s1,s2)
     char *s1,*s2;
{
  register int diff = 0;

  while (*s1 && *s2) diff += abs(*s1++ - *s2++);
  while (*s1) diff += *s1++;
  while (*s2) diff += *s2++;
  return(diff);
}

scanpdir(dir,name,
	 family,point,mag,
	 bestfamily,bestname,bestpoint,bestmag,
	 min_df,min_dp,min_dm)
     char *dir,*name,*family,*bestfamily,*bestname;
     int point,mag,*bestpoint,*bestmag,*min_df,*min_dp,*min_dm;
{
  DIR *dirstream;
  struct direct *dirrecord;
  char qfamily[NFNTCHARS];
  int qpoint,qmag,df,dp,dm;

  if (dirstream = opendir(dir)) {
    while (dirrecord = readdir(dirstream)) {
#ifdef USEPXL
      if (!strcmp(dirrecord->d_name+dirrecord->d_namlen-3,"pxl")) {
#else
      if (!strcmp(dirrecord->d_name+dirrecord->d_namlen-2,"gf")) {
#endif
	qpoint = -1; qmag = -1;
	(void) sscanf(dirrecord->d_name,"%[^0123456789.]%d.%d",
		      qfamily,&qpoint,&qmag);
	df = strdiff(family,qfamily);
	dp = abs(point - qpoint);
	dm = abs(mag - qmag);
	if ((df < *min_df)
	    || (df == *min_df && dp < *min_dp)
	      || (df == *min_df && dp == *min_dp && dm < *min_dm)) {
		sprintf(bestname,"%s/%s",dir,dirrecord->d_name);
		strcpy(bestfamily,qfamily);
		*bestpoint = qpoint;
		*bestmag = qmag;
		*min_df = df;
		*min_dp = dp;
		*min_dm = dm;
	  }
      }
    }
    closedir(dirstream);
  }
}

scandir(dir,name,
	family,point,mag,
	bestfamily,bestname,bestpoint,bestmag,
	min_df,min_dp,min_dm)
     char *dir,*name,*family,*bestfamily,*bestname;
     int point,mag,*bestpoint,*bestmag,*min_df,*min_dp,*min_dm;
{
  DIR *dirstream;
  struct direct *dirrecord;
  int df;
  char pdir[MAXNAMLEN];

  if (dirstream = opendir(dir)) {
    while (dirrecord = readdir(dirstream)) {
      if (dirrecord->d_name[0] != '.') {
	df = strdiff(name,dirrecord->d_name);
	if (df <= *min_df) {
	  sprintf(pdir,"%s/%s",dir,dirrecord->d_name);
	  scanpdir(pdir,name,
		   family,point,mag,
		   bestfamily,bestname,bestpoint,bestmag,
		   min_df,min_dp,min_dm);
	}
      }
    }
    closedir(dirstream);
  }
}


/* finds the best match to the desired font */
int findanyfile(dirvec,dirveclen,family,point,mag,name,s,nname,nmag)
     char *dirvec[],*family,*name,*s,*nname;
     int dirveclen,point,mag,*nmag;
{
  char foo[MAXNAMLEN],bestname[MAXNAMLEN],bestfamily[NFNTCHARS];
  int min_df,min_dp,min_dm,df,dp,dm,i,bestpoint,bestmag;
  
  bestname[0] = '\0'; 
  min_df = min_dp = min_dm = 9999999;
  for (i = 0; i < dirveclen; i++) {
    sprintf(foo,"%s/SUBDIR",dirvec[i]);
    if (!access(foo,0)) scandir(dirvec[i],name,
				family,point,mag,
				bestfamily,bestname,&bestpoint,&bestmag,
				&min_df,&min_dp,&min_dm);
    else scanpdir(dirvec[i],name,
		  family,point,mag,
		  bestfamily,bestname,&bestpoint,&bestmag,
		  &min_df,&min_dp,&min_dm);
  }
  if (bestname[0]) {
    if (bestpoint > 0) sprintf(nname,"%s%d",bestfamily,bestpoint);
    else strcpy(nname,bestfamily);
    *nmag = bestmag;
    strcpy(s,bestname);
    if ((strcmp(bestfamily,family)
	 || bestpoint != point || abs(bestmag - mag) > 2)) 
      fprintf(stderr,
	      "Substituted font %s at mag %d for %s at mag %d.\n",
	      nname,(bestmag * 4 + 3) / 6,
	      name,(mag * 4 + 3) / 6);
    return(-1);
  }
  return(0);
}
  
SHAR_EOF
if test 5047 -ne "`wc -c findfile.c`"
then
echo shar: error transmitting findfile.c '(should have been 5047 characters)'
fi
echo shar: extracting findfile.h '(246 characters)'
cat << \SHAR_EOF > findfile.h
/* findfile.h
 * Copyright 1985 Massachusetts Institute of Technology
 */

extern int findfile();
/* int findfile(dirvec,dirveclen,area, name, mag, s, nname, nmag)
 *     char *dirvec[],*area,*name,*s,*nname;
 *     int dirveclen,mag,*nmag;
 */

SHAR_EOF
if test 246 -ne "`wc -c findfile.h`"
then
echo shar: error transmitting findfile.h '(should have been 246 characters)'
fi
echo shar: extracting gf.c '(8930 characters)'
cat << \SHAR_EOF > gf.c
#ifndef USEPXL
#include	<stdio.h>

#define false	0
#define true	1

/* This file contains routines for reading character descriptions from
   GF files (the output of Metafont).  The following functions are defined:
   gettochar()	finds the next character, returns its code (reduced modulo
		256 if necessary), and sets global variables min_m, max_m,
		min_n, max_n.  A result of -1 indicates that there are no
		more characters and the postamble has been found.
   readbits()	After a character is found, this routine fills array bits[]
		with the character image.  The image is represented in
		Postscript format: the bits are packed into bytes
		(most significant bit first), and the bytes scan the image
		left-to-right, bottom-to-top.
		Set globals num_cols, num_rows, x_offset, y_offset
		(the latter give the offset of the origin from the upper
		bottom corner of the image, up being a positive y_offset).
   readpost()	After the postamble is found, this routine reads it and
		sets the remaining global variables declared below.
   seekpost()	rapidly finds the postamble by random accessing the file.
   seekchar(c)	uses fseek() to find a character with code c (modulo 256),
		returning a nonzero result if successful.  Global variables
		are set as they are by gettochar.  GF files may contain
		many characters with the same code, in which case subsequent
		calls to seekchar(c) with the same c will find the other
		versions.  This routine should only be called after readpost().
   No random access is attempted if seekpost() and seekchar() are not used.
*/

#define int32	long		/* used when at least 32 bits are required */

int min_m, max_m, min_n, max_n;	/* bounding box for character */
int32 charfam;			/* high order bytes of character code */

int font_min_m, font_max_m, font_min_n, font_max_n;	/* overall bounds */
int32 designsize;	/* font size in points scaled by 1<<20 */
int32 checksum;		/* should match TFM file and DVI file */
int32 hppp, vppp;	/* horizontal and vertical pixels/point scaled 1<<16 */
int char_wd[256];	/* character width in pixels, rounded if necessary */
int32 tfm_wd[256];	/* width as a fraction of designsize scaled 1<<20 */
char char_exists[256];	/* nonzero entries indicate presence of a char_loc */
int gf_bc, gf_ec;	/* first and last nonzero char_exists entries */

int32 char_pointer[256];	/* used by seekchar() */
int32 backpointer;		/* set by gettochar() for use by seekchar() */


void gf_beginc();	/* prepare to paint white at (min_m,max_n) */
void gf_paint();	/* paint d pixels and switch colors */
void gf_skip();		/* finish a row and skip d rows */
void gf_endc();		/* finish the last row */

extern void bad_gf();	/* aborts the program if the gf file is invalid */ 
FILE *gfin=stdin;	/* change this externally if necessary */


/* The following macros describe gf file format */

#define paint_0		0
#define last_paint	63
#define paint1		64
#define paint2		65
#define paint3		66
#define boc		67
#define boc1		68
#define eoc		69
#define skip0		70
#define skip1		71
#define skip2		72
#define skip3		73
#define new_row_0	74
#define last_new_row	238
#define xxx1		239
#define xxx2		240
#define xxx3		241
#define xxx4		242
#define yyy		243
#define no_op		244
#define char_loc	245
#define char_loc0	246
#define pre		247
#define post		248
#define postpost	249
#define undefined_cases	250: case 251: case 252: case 253: case 254: case 255
#define gf_version	131



/* All gf file input goes through the following routines */

#define getbyte()	(getc(gfin)&0xff)
/* int getbyte()
{
	int b;
	b=getc(gfin)&0xff;
	printf("Getting %d\n",b);
	return b;
} */

#define skip1byte()	getc(gfin)

int get2bytes()
{	register int ans;
	ans=getbyte()<<8; ans+=getbyte();
	return ans;
}

int32 get3bytes()
{	register int32 ans;
	ans=getbyte()<<16;
	ans+=getbyte()<<8;
	ans+=getbyte();
	return ans;
}

int32 get4bytes()
{
	register int32 ans;
	ans=getbyte()<<24;
	ans+=getbyte()<<16;
	ans+=getbyte()<<8;
	ans+=getbyte();
	return ans;
}

void skip_bytes(n)
	int n;
{
	while (n-- >0) skip1byte();
}



/* In the unlikely event of a character code outside of the range 0..255,
   the high order bytes are placed in the global variable charfam.
   If no boc command is encountered, the result is -1 and the last byte read
   is guaranteed to be the post command.
*/
int gettochar()
{
	int32 c;		/* the character code to be returned */
	register int x;		/* temporary */

	for(;;) switch(getbyte())
	{
	case yyy: skip1byte();		/* intended to fall through 3 times */
	case paint3: case skip3: skip1byte();
	case paint2: case skip2: skip1byte();
	case paint1: case skip1: skip1byte(); continue;

	case boc: c=get4bytes();
		backpointer=get4bytes();
		min_m=get4bytes();
		max_m=get4bytes();
		min_n=get4bytes();
		max_n=get4bytes();
		charfam = c<0 ? -((-c)>>8) : c>>8;
		return c&0377;

	case boc1: c=getbyte();
		backpointer= -1;
		x=getbyte();		/* del_m */
		max_m=getbyte();
		min_m=max_m-x;
		x=getbyte();		/* del_n */
		max_n=getbyte();
		min_n=max_n-x;
		return c;

	case pre: if (getbyte()!=gf_version) bad_gf(1);
		skip_bytes(getbyte());
		continue;

	case xxx1: skip_bytes(getbyte()); continue;
	case xxx2: skip_bytes(get2bytes()); continue;
	case xxx3: skip_bytes((int) get3bytes()); continue;
	case xxx4: skip_bytes((int) get4bytes()); continue;

	case post: return -1;

	case char_loc: case char_loc0: case postpost: case undefined_cases:
		bad_gf(2);

	default: /* do nothing */;
	}
}


/* readbits reads a raster description from the gf file and uses the external
   routines to actually process the raster information.
*/
void readbits()
{
	register unsigned char b;

	gf_beginc();
	for (;;) {
		b=getbyte();
		if (b<=last_paint) gf_paint(b-paint_0);
		if (b<new_row_0)
			switch(b)
			{
			case paint1: gf_paint(getbyte()); continue;
			case paint2: gf_paint(get2bytes()); continue;
			case paint3: gf_paint((int) get3bytes()); continue;
			case boc: case boc1: bad_gf(3);
			case eoc: goto finish;
			case skip0: gf_skip(0); continue;
			case skip1: gf_skip(getbyte()); continue;
			case skip2: gf_skip(get2bytes()); continue;
			case skip3: gf_skip((int) get3bytes()); continue;
			}
		else if (b<=last_new_row) {
			gf_skip(0);
			gf_paint(b-new_row_0);
		} else switch(b)
			{
			case xxx1: skip_bytes(getbyte()); continue;
			case xxx2: skip_bytes(get2bytes()); continue;
			case xxx3: skip_bytes((int) get3bytes()); continue;
			case xxx4: skip_bytes((int) get4bytes()); continue;
			case yyy: get4bytes(); continue;
			case no_op: continue;
			default: bad_gf(4);
			}
	}
finish:	gf_endc();
}



void readpost()
{
	int i, b, c;

	get4bytes();	/* ignore back pointer to font-wide xxx commands */
	designsize=get4bytes();
	checksum=get4bytes();
	hppp=get4bytes();
	vppp=get4bytes();
	font_min_m=get4bytes();
	font_max_m=get4bytes();
	font_min_n=get4bytes();
	font_max_n=get4bytes();

	for(i=0; i<256; i++) {
		char_exists[i]=false;
		char_wd[i]=0;
		tfm_wd[i]=0;
		char_pointer[i]= -1;
	}
	gf_bc=255;
	gf_ec=0;
	for (;;) {
		b=getbyte();
		c=getbyte();
		if (b==char_loc0) char_wd[c]=getbyte();
		else if (b==char_loc) {
			char_wd[c]=(get4bytes()+0100000)>>16;
			get4bytes();		/* skip dy */
		} else break;
		tfm_wd[c]=get4bytes();
		char_pointer[c]=get4bytes();
		char_exists[c]=true;
		if (gf_bc>c) gf_bc=c;
		if (gf_ec<c) gf_ec=c;
	}
}



void seekpost()
{
	int c;
	fseek(gfin, -5L, 2);			/* skip four 223's */
	do {	c=getbyte();
		fseek(gfin, -2L, 1);
	} while (c==223);
	if (c!=gf_version) bad_gf(5);		/* check version number */
	fseek(gfin, -3L, 1);			/* back up to the pointer */
	if (fseek(gfin, (long) get4bytes(), 0) < 0) bad_gf(6);
	if (getbyte()!=post) bad_gf(7);
}


int seekchar(c)
	int c;
{
	if (c<0 || c>255 || char_pointer[c]<0) return false;
	if (fseek(gfin, char_pointer[c], 0) < 0) bad_gf(8);
	if (gettochar()!=c) bad_gf(9);
	char_pointer[c]=backpointer;
	return true;
}

#define BITBUFSIZE 20000
unsigned char bits[BITBUFSIZE];
int num_cols, num_rows, num_bytes, x_offset, y_offset;
#define row_start(n) (&(bits[(n-min_n)*rowbytes]))
#define m_byte(m) ((m-min_m)>>3)	/* byte within within a row containing bit m */
#define m_bit(m) (7-(m-min_m)&07)	/* bit within byte for a given m */

static int rowbytes, gf_m0, gf_m, gf_n, paint_switch;
static unsigned char *row_ptr;

void gf_beginc()
{
	num_cols=max_m-min_m+1;
	num_rows=max_n-min_n+1;
	x_offset= -min_m;
	y_offset= -min_n;
	rowbytes=(num_cols+7)/8;
	num_bytes=num_rows*rowbytes;
	if (num_bytes>=BITBUFSIZE)
		bad_gf(10); /* really, should allocate a bigger one */
	gf_m=gf_m0=min_m;
	gf_n=max_n;
	row_ptr=row_start(max_n);
	bzero(bits, num_bytes);
	paint_switch=0;
}

void gf_paint(d)
	register int d;
{
	if (d>0) {
		if (paint_switch)
			while (d-- >0) {
				row_ptr[m_byte(gf_m)] |= 1<<m_bit(gf_m);
				gf_m++;
			}
		else
			gf_m += d;
	}
	paint_switch ^= 1;
}

void gf_skip(d)
	int d;
{
	gf_n -= d+1;
	gf_m=gf_m0;
	row_ptr=row_start(gf_n);
	paint_switch=0;
}

void gf_endc() { /* do nothing */ }
#endif
SHAR_EOF
if test 8930 -ne "`wc -c gf.c`"
then
echo shar: error transmitting gf.c '(should have been 8930 characters)'
fi
#	End of shell archive
exit 0