[net.sources] DVIDOC for Pyramid OSx

simpson@trwrb.UUCP (Scott Simpson) (09/10/86)

    Here is a copy of the DVIDOC program posted by Clayton Elwell 
(elwell@osu-eddie) of Ohio State University.  This version runs on
Pyramid OSx using the Pyramid pascal compiler.  The previous
posted version did not run under OSx (it did not even weave
or compile).  Also, the old doc.pl file was outdated.  I have also
created a Makefile and man page for the program.  I do not expect
this version to run under the 4.2 pc compiler although I have not
tried it.
    The file seek algorithm is horrible and causes the program to run
very slow on large DVI files.  In fact, if you looked up horrible in the
dictionary you would probably see a picture of my seek code there.
    You will need to modify the pathnames in the files appropriately.
Also, this file is one big shar file posted in two parts so you will
have to cat them together and then unshar them.  The dvidoc.web file
was over 66K bytes so posting it individually still could have caused
problems.
		Scott Simpson
		TRW Electronics and Defense Sector
		...{decvax,ihnp4,ucbvax}!trwrb!simpson
#! /bin/sh
# To extract, remove mail header lines and type "sh filename"
if [ ! -d dvidoc ]
then
	mkdir dvidoc
	echo mkdir dvidoc
fi
echo x - dvidoc/Makefile
sed -e 's/^X//' > dvidoc/Makefile << '!FaR!OuT!'
XDEST=/usr/local/bin
XLIB=/usr/local/lib/tex/fonts
XMACROS=/usr/local/lib/tex/macros
XPC=pascal
XPFLAGS=-O
XLDFLAGS=-s
X
X.SUFFIXES: .web .o .dvi .pl .tfm
X.web.o:
X	tangle $<
X	$(PC) -c $(PFLAGS) $*.p
X	rm $*.p
X.web.dvi:
X	weave $<
X	tex $*.tex
X	rm $*.tex
X.pl.tfm:
X	pltotf $< $*.tfm
X
Xall: dvidoc doc.tfm dvidoc.dvi
X
Xdvidoc: dvidoc.o dvityext.o
X	$(PC) -o $@ $(LDFLAGS) dvidoc.o dvityext.o
X
Xinstall: all
X	install -m 644 doc.tfm $(LIB)
X	install -m 755 dvidoc $(DEST)
X	install -m 644 -c docmac.tex $(MACROS)
X
Xclean:
X	-rm -f *.o dvidoc.p dvidoc dvidoc.log dvidoc.tex dvidoc.pool \
X	CONTENTS.tex dvidoc.dvi doc.tfm
X
!FaR!OuT!
if [ ! -d dvidoc ]
then
	mkdir dvidoc
	echo mkdir dvidoc
fi
echo x - dvidoc/doc.pl
sed -e 's/^X//' > dvidoc/doc.pl << '!FaR!OuT!'
X(COMMENT OSU DOC file font)
X(COMMENT Derived from amtt)
X(CODINGSCHEME TEX TYPEWRITER TEXT)
X(DESIGNSIZE R 13.76574)
X(COMMENT DESIGNSIZE IS IN POINTS)
X(COMMENT OTHER SIZES ARE MULTIPLES OF DESIGNSIZE)
X(CHECKSUM O 10653670734)
X(SEVENBITSAFEFLAG TRUE)
X(FONTDIMEN
X   (SLANT R 0.0)
X   (SPACE R 0.5249996)
X   (STRETCH R 1.049999)
X   (SHRINK R 0.0)
X   (XHEIGHT R 0.4305553)
X   (QUAD R 0.5249996)
X   (EXTRASPACE R 0.5249996)
X   )
X(LIGTABLE
X   (LABEL O 47)
X   (LIG O 47 O 42)
X   (STOP)
X   (LABEL O 140)
X   (LIG O 140 O 42)
X   (STOP)
X   )
X(CHARACTER O 41
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER O 42
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER O 43
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER O 44
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6944446)
X   (CHARDP R 0.0833330)
X   )
X(CHARACTER O 45
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6944446)
X   (CHARDP R 0.0833330)
X   )
X(CHARACTER O 46
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER O 47
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER O 50
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6944446)
X   (CHARDP R 0.0833330)
X   )
X(CHARACTER O 51
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6944446)
X   (CHARDP R 0.0833330)
X   )
X(CHARACTER O 52
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.5208330)
X   )
X(CHARACTER O 53
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.5097217)
X   )
X(CHARACTER O 54
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.1000003)
X   (CHARDP R 0.1111106)
X   )
X(CHARACTER O 55
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.5097217)
X   )
X(CHARACTER O 56
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.1000003)
X   )
X(CHARACTER O 57
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6944446)
X   (CHARDP R 0.0833330)
X   )
X(CHARACTER C 0
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C 1
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C 2
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C 3
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C 4
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C 5
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C 6
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C 7
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C 8
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C 9
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER O 72
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   )
X(CHARACTER O 73
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   (CHARDP R 0.1111106)
X   )
X(CHARACTER O 74
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.5555553)
X   )
X(CHARACTER O 75
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4156246)
X   )
X(CHARACTER O 76
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.5555553)
X   )
X(CHARACTER O 77
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER O 100
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C A
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C B
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C C
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C D
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C E
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C F
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C G
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C H
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C I
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C J
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C K
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C L
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C M
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C N
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C O
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C P
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C Q
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   (CHARDP R 0.1111106)
X   )
X(CHARACTER C R
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C S
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C T
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C U
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C V
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C W
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C X
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C Y
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C Z
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER O 133
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6944446)
X   (CHARDP R 0.0833330)
X   )
X(CHARACTER O 134
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6944446)
X   (CHARDP R 0.0833330)
X   )
X(CHARACTER O 135
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6944446)
X   (CHARDP R 0.0833330)
X   )
X(CHARACTER O 136
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER O 137
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.5381946)
X   )
X(CHARACTER O 140
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C a
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   )
X(CHARACTER C b
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C c
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   )
X(CHARACTER C d
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C e
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   )
X(CHARACTER C f
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C g
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   (CHARDP R 0.2222223)
X   )
X(CHARACTER C h
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C i
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C j
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   (CHARDP R 0.2222223)
X   )
X(CHARACTER C k
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C l
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
X(CHARACTER C m
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   )
X(CHARACTER C n
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   )
X(CHARACTER C o
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   )
X(CHARACTER C p
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   (CHARDP R 0.2222223)
X   )
X(CHARACTER C q
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   (CHARDP R 0.2222223)
X   )
X(CHARACTER C r
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   )
X(CHARACTER C s
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   )
X(CHARACTER C t
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.5659723)
X   )
X(CHARACTER C u
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   )
X(CHARACTER C v
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   )
X(CHARACTER C w
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   )
X(CHARACTER C x
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   )
X(CHARACTER C y
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   (CHARDP R 0.2222223)
X   )
X(CHARACTER C z
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.4305553)
X   )
X(CHARACTER O 173
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6944446)
X   (CHARDP R 0.0833330)
X   )
X(CHARACTER O 174
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6944446)
X   (CHARDP R 0.0833330)
X   )
X(CHARACTER O 175
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6944446)
X   (CHARDP R 0.0833330)
X   )
X(CHARACTER O 176
X   (CHARWD R 0.5249996)
X   (CHARHT R 0.6111106)
X   )
!FaR!OuT!
if [ ! -d dvidoc ]
then
	mkdir dvidoc
	echo mkdir dvidoc
fi
echo x - dvidoc/docmac.tex
sed -e 's/^X//' > dvidoc/docmac.tex << '!FaR!OuT!'
X\baselineskip=12bp
X\font\docfont=doc
X\textfont0=\docfont \scriptfont0=\docfont \scriptscriptfont0=\docfont
X\def\rm{\fam0\docfont}
X\textfont1=\docfont \scriptfont1=\docfont \scriptscriptfont1=\docfont
X\def\mit{\fam1} \def\oldstyle{\fam1\docfont}
X\def\it{\fam\itfam\docfont} % \it is family 4
X\textfont\itfam=\docfont
X\def\sl{\fam\slfam\docfont} % \sl is family 5
X\textfont\slfam=\docfont
X\def\bf{\fam\bffam\docfont} % \bf is family 6
X\textfont\bffam=\docfont \scriptfont\bffam=\docfont
X\scriptscriptfont\bffam=\docfont
X\def\tt{\fam\ttfam\docfont} % \tt is family 7
X\textfont\ttfam=\docfont
X\def\TeX{TeX}
X\def\LaTeX{LaTeX}
X\def\SliTeX{SliTeX}
X\def\BibTeX{BibTeX}
X\rm
!FaR!OuT!
if [ ! -d dvidoc ]
then
	mkdir dvidoc
	echo mkdir dvidoc
fi
echo x - dvidoc/dvidoc.1
sed -e 's/^X//' > dvidoc/dvidoc.1 << '!FaR!OuT!'
X.\" $Header
X.if t .ds TX T\h'-.1667m'\v'.22m'E\h'-.125m'\v'-.22m'X
X.if n .ds TX TeX
X.if t .ds LX L\v'-.22m'a\v'.22m'T\h'-.1667m'\v'.22m'E\h'-.125m'\v'-.22m'X
X.if n .ds LX LaTeX
X.TH DVIDOC 1
X.UC
X.SH NAME
Xdvidoc \- print TeX DVI files out on a file
X.SH SYNOPSIS
Xdvidoc
X.I dvifile
X.I outputfile
X.SH DESCRIPTION
X.IR Dvidoc (1)
Xattempts to print the contents of a DVI file on a regular ASCII file.
XThe output file will not be an exact representation of the DVI file
Xsince \*(TX output is designed for a high-resolution device.
XThe output will be an approximate representation of paragraph breaks
Xand it provides a simple quick means to preview output at your terminal.
XMath mode and tables are not handled well.
XAlso, page breaks will be different when output to a high-resolution device.
X.PP
XTo use 
X.I dvidoc
Xyou must 
X.I \input
Xthe macro file
X.I docmac.tex
Xin the beginning of your \*(TX or \*(LX document.
XThis file redefines the width of the roman, italic, boldface and typewriter
Xfonts.
XWhen you wish to output the final document to the laser printer or other
Xhigh resolution device you should remove the include file
X.I docmac.tex
Xand re\*(TX your document.
X.SH FILES
X.nf
X.ta \w'/usr/local/lib/tex/macros/docmac.tex   'u
X/usr/local/lib/tex/macros/docmac.tex	Input macro package
X.fi
X.SH SEE ALSO
Xtex(1)
X.SH BUGS
XThe DVI seek algorithm is horrible so it runs forever on large DVI files.
!FaR!OuT!
if [ ! -d dvidoc ]
then
	mkdir dvidoc
	echo mkdir dvidoc
fi
echo x - dvidoc/dvidoc.web
sed -e 's/^X//' > dvidoc/dvidoc.web << '!FaR!OuT!'
X% This is DVIDOC, a TeX device driver for text files.  It was written
X% at OSU in April, 1983, by modifying the TeX utility DVItype.
X
X% Here is TeX material that gets inserted after \input webhdr
X\def\hang{\hangindent 3em\indent\ignorespace}
X\def\TeX{T\hbox{\hskip-.1667em\lower.424ex\hbox{E}\hskip-.125em X}}
X\font\ninerm=cmr9
X\let\mc=\ninerm % medium caps for names like PASCAL
X\def\PASCAL{{\mc PASCAL}}
X
X\def\(#1){} % this is used to make module names sort themselves better
X\def\9#1{} % this is used for sort keys in the index
X
X\def\title{DVIDOC}
X\def\contentspagenumber{1}
X\def\topofcontents{\null
X  \def\titlepage{F} % include headline on the contents page
X  \def\rheader{\mainfont\hfil \contentspagenumber}
X  \vfill
X  \centerline{\titlefont The {\ttitlefont DVIDOC} processor}
X  \vskip 15pt
X  \centerline{(Version 1, April 1983)}
X  \vfill}
X\def\botofcontents{\vfill
X  \centerline{\hsize 5in\baselineskip9pt
X    \vbox{\ninerm\noindent
X   `\TeX' is a
X    trademark of the American Mathematical Society.}}}
X\pageno=\contentspagenumber \advance\pageno by 1
X
X@* Introduction.
XThe \.{DVIDOC} utility program reads binary device-independent (``\.{DVI}'')
Xfiles that are produced by document compilers such as \TeX, and 
Xapproximates the intended document as a text file suitable for typing at
Xa terminal or on a line printer.
X
XThis program is based on the program \.{DVItype}, which was written by
XDonald Knuth and David Fuchs.
XIt contained a great deal of code checking for malformed \.{DVI}
Xfiles.  Most of that code remains in \.{DVIDOC}, not because it is
Ximportant (we trust \TeX) to produce correct \.{DVI} files), but
Xbecause is was easier not to disturb the logic in modifying
X\.{DVItype} to produce \.{DVIDOC}.
X
XThe |banner| string defined here should be changed whenever \.{DVIDOC}
Xgets modified.
X
X@d banner=='This is DVIDOC, Version 1 for Pyramid OSx' {printed when the program starts}
X
X@ Unlike the programs distributed with \TeX, which are written in a
Xleast-common-denominator Pascal that runs on no machine, this program
Xis written to run on OSx using Pyramid Pascal.  
X
X@d othercases == otherwise: {default for cases not listed explicitly}
X@d endcases == @+end {follows the default case in an extended |case| statement}
X@f othercases == else
X@f endcases == end
X
X@ The binary input comes from |dvi_file|, and the document is written
Xon the file |doc_file|
X|term_in| and |term_out| are used throughout this program as files for
Xdialog with the user.  
X
X@d term_in==input
X@d term_out==output
X@d error(#)==message(' ',#)
X
X@p program DVIDOC(@!dvi_file,@!doc_file);
Xlabel @<Labels in the outer block@>@/
Xconst @<Constants in the outer block@>@/
Xtype @<Types in the outer block@>@/
Xvar@?@<Globals in the outer block@>@/
X@\@=#include "dvityext.h"@>@\ {declarations for external C procedures}
Xprocedure initialize; {this procedure gets things started properly}
Xvar i:integer;
X  begin @/
X  setpaths;
X  @<Set initial values@>@/
X  end;
X
X@ If the program has to stop prematurely, it goes to the
X`|final_end|'. Another label, |done|, is used when stopping normally.
X
X@d final_end=9999 {label for the end of it all}
X@d done=30 {go here when finished with a subtask}
X
X@<Labels...@>=final_end,done;
X
X@ The following parameters can be changed at compile time to extend or
Xreduce \.{DVIDOC}'s capacity.
X
X@<Constants...@>=
X@!max_fonts=100; {maximum number of distinct fonts per \.{DVI} file}
X@!max_widths=10000; {maximum number of different characters among all fonts}
X@!terminal_line_length=150; {maximum number of characters input in a single
X  line of input from the terminal}
X@!stack_size=100; {\.{DVI} files shouldn't |push| beyond this depth}
X@!name_size=1000; {total length of all font file names}
X@!name_length=100; {a file name shouldn't be longer than this}
X@!page_width_max=132; {maximum number of characters per line in the document}
X@!page_length_max=88; {maximum number of lines per page in the document}
X
X@ Here are some macros for common programming idioms.
X
X@d incr(#) == #:=#+1 {increase a variable by unity}
X@d decr(#) == #:=#-1 {decrease a variable by unity}
X@d do_nothing == {empty statement}
X
X@ If the \.{DVI} file is badly malformed, the whole process must be aborted;
X\.{DVIDOC} will give up, after issuing an error message about the symptoms
Xthat were noticed.
X
XSuch errors might be discovered inside of subroutines inside of subroutines,
Xso a procedure called |jump_out| has been introduced. This procedure, which
Xsimply transfers control to the label |final_end| at the end of the program,
Xcontains the only non-local |goto| statement in \.{DVIDOC}.
X
X@d abort(#)==begin message(' ',#); jump_out;
X    end
X@d bad_dvi(#)==abort('Bad DVI file: ',#,'!')
X@.Bad DVI file@>
X
X@p procedure jump_out;
Xbegin goto final_end;
Xend;
X
X@* The character set.
XLike all programs written with the  \.{WEB} system, \.{DVIDOC} can be
Xused with any character set. But it uses ascii code internally, because
Xthe programming for portable input-output is easier when a fixed internal
Xcode is used, and because \.{DVI} files use ascii code for file names
Xand certain other strings.
X
XThe next few modules of \.{DVIDOC} have therefore been copied from the
Xanalogous ones in the \.{WEB} system routines. They have been considerably
Xsimplified, since \.{DVIDOC} need not deal with the controversial
Xascii codes less than @'40. If such codes appear in the \.{DVI} file,
Xthey will be printed as question marks.
X
X@<Types...@>=
X@!ascii_code=" ".."~"; {a subrange of the integers}
X
X@ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
Xcharacter sets were common, so it did not make provision for lower case
Xletters. Nowadays, of course, we need to deal with both upper and lower case
Xalphabets in a convenient way, especially in a program like \.{DVIDOC}.
XSo we shall assume that the \PASCAL\ system being used for \.{DVIDOC}
Xhas a character set containing at least the standard visible characters
Xof ascii code (|"!"| through |"~"|).
X
XSome \PASCAL\ compilers use the original name |char| for the data type
Xassociated with the characters in text files, while other \PASCAL s
Xconsider |char| to be a 64-element subrange of a larger data type that has
Xsome other name.  In order to accommodate this difference, we shall use
Xthe name |text_char| to stand for the data type of the characters in the
Xoutput file.  We shall also assume that |text_char| consists of
Xthe elements |chr(first_text_char)| through |chr(last_text_char)|,
Xinclusive. The following definitions should be adjusted if necessary.
X@d text_char == char {the data type of characters in text files}
X@d first_text_char=0 {ordinal number of the smallest element of |text_char|}
X@d last_text_char=127 {ordinal number of the largest element of |text_char|}
X
X@<Types...@>=
X@!text_file=packed file of text_char;
X
X@ The \.{DVIDOC} processor converts between ascii code and
Xthe user's external character set by means of arrays |xord| and |xchr|
Xthat are analogous to \PASCAL's |ord| and |chr| functions.
X
X@<Globals...@>=
X@!xord: array [text_char] of ascii_code;
X  {specifies conversion of input characters}
X@!xchr: array [0..255] of text_char;
X  {specifies conversion of output characters}
X
X@ Under our assumption that the visible characters of standard ascii are
Xall present, the following assignment statements initialize the
X|xchr| array properly, without needing any system-dependent changes.
X
X@<Set init...@>=
Xfor i:=0 to @'37 do xchr[i]:='?';
Xxchr[@'40]:=' ';
Xxchr[@'41]:='!';
Xxchr[@'42]:='"';
Xxchr[@'43]:='#';
Xxchr[@'44]:='$';
Xxchr[@'45]:='%';
Xxchr[@'46]:='&';
Xxchr[@'47]:='''';@/
Xxchr[@'50]:='(';
Xxchr[@'51]:=')';
Xxchr[@'52]:='*';
Xxchr[@'53]:='+';
Xxchr[@'54]:=',';
Xxchr[@'55]:='-';
Xxchr[@'56]:='.';
Xxchr[@'57]:='/';@/
Xxchr[@'60]:='0';
Xxchr[@'61]:='1';
Xxchr[@'62]:='2';
Xxchr[@'63]:='3';
Xxchr[@'64]:='4';
Xxchr[@'65]:='5';
Xxchr[@'66]:='6';
Xxchr[@'67]:='7';@/
Xxchr[@'70]:='8';
Xxchr[@'71]:='9';
Xxchr[@'72]:=':';
Xxchr[@'73]:=';';
Xxchr[@'74]:='<';
Xxchr[@'75]:='=';
Xxchr[@'76]:='>';
Xxchr[@'77]:='?';@/
Xxchr[@'100]:='@@';
Xxchr[@'101]:='A';
Xxchr[@'102]:='B';
Xxchr[@'103]:='C';
Xxchr[@'104]:='D';
Xxchr[@'105]:='E';
Xxchr[@'106]:='F';
Xxchr[@'107]:='G';@/
Xxchr[@'110]:='H';
Xxchr[@'111]:='I';
Xxchr[@'112]:='J';
Xxchr[@'113]:='K';
Xxchr[@'114]:='L';
Xxchr[@'115]:='M';
Xxchr[@'116]:='N';
Xxchr[@'117]:='O';@/
Xxchr[@'120]:='P';
Xxchr[@'121]:='Q';
Xxchr[@'122]:='R';
Xxchr[@'123]:='S';
Xxchr[@'124]:='T';
Xxchr[@'125]:='U';
Xxchr[@'126]:='V';
Xxchr[@'127]:='W';@/
Xxchr[@'130]:='X';
Xxchr[@'131]:='Y';
Xxchr[@'132]:='Z';
Xxchr[@'133]:='[';
Xxchr[@'134]:='\';
Xxchr[@'135]:=']';
Xxchr[@'136]:='^';
Xxchr[@'137]:='_';@/
Xxchr[@'140]:='`';
Xxchr[@'141]:='a';
Xxchr[@'142]:='b';
Xxchr[@'143]:='c';
Xxchr[@'144]:='d';
Xxchr[@'145]:='e';
Xxchr[@'146]:='f';
Xxchr[@'147]:='g';@/
Xxchr[@'150]:='h';
Xxchr[@'151]:='i';
Xxchr[@'152]:='j';
Xxchr[@'153]:='k';
Xxchr[@'154]:='l';
Xxchr[@'155]:='m';
Xxchr[@'156]:='n';
Xxchr[@'157]:='o';@/
Xxchr[@'160]:='p';
Xxchr[@'161]:='q';
Xxchr[@'162]:='r';
Xxchr[@'163]:='s';
Xxchr[@'164]:='t';
Xxchr[@'165]:='u';
Xxchr[@'166]:='v';
Xxchr[@'167]:='w';@/
Xxchr[@'170]:='x';
Xxchr[@'171]:='y';
Xxchr[@'172]:='z';
Xxchr[@'173]:='{';
Xxchr[@'174]:='|';
Xxchr[@'175]:='}';
Xxchr[@'176]:='~';
Xfor i:=@'177 to 255 do xchr[i]:='?';
X
X@ The following system-independent code makes the |xord| array contain a
Xsuitable inverse to the information in |xchr|.
X
X@<Set init...@>=
Xfor i:=first_text_char to last_text_char do xord[chr(i)]:=@'40;
Xfor i:=" " to "~" do xord[xchr[i]]:=i;
X
X@* Device-independent file format.
XThe device-independent file format is described in the \.{DVItype} 
Xdocumentation.
X
XWhen \.{DVIDOC} "typesets" a character, it simply puts its ascii code
Xinto the document file in the proper place according to the rounding of
X|h| and |v| to whole character positions.  It may, of course, obliterate
Xa character previously stored in the same position.  Especially if a
Xsymbol font is being used, the ascii code may print ultimately as an
Xentirely different character than the one the document designer originally
Xintended.  For \.{DVIDOC} to produce more than a rough approximation to 
Xthe intended document, fonts need to be chosen very carefully.
X
X@ @d set_char_0=0 {typeset character 0 and move right}
X@d set1=128 {typeset a character and move right}
X@d set_rule=132 {typeset a rule and move right}
X@d put1=133 {typeset a character}
X@d put_rule=137 {typeset a rule}
X@d nop=138 {no operation}
X@d bop=139 {beginning of page}
X@d eop=140 {ending of page}
X@d push=141 {save the current positions}
X@d pop=142 {restore previous positions}
X@d right1=143 {move right}
X@d w0=147 {move right by |w|}
X@d w1=148 {move right and set |w|}
X@d x0=152 {move right by |x|}
X@d x1=153 {move right and set |x|}
X@d down1=157 {move down}
X@d y0=161 {move down by |y|}
X@d y1=162 {move down and set |y|}
X@d z0=166 {move down by |z|}
X@d z1=167 {move down and set |z|}
X@d fnt_num_0=171 {set current font to 0}
X@d fnt1=235 {set current font}
X@d xxx1=239 {extension to \.{DVI} primitives}
X@d xxx4=242 {potentially long extension to \.{DVI} primitives}
X@d fnt_def1=243 {define the meaning of a font number}
X@d pre=247 {preamble}
X@d post=248 {postamble beginning}
X@d post_post=249 {postamble ending}
X@d undefined_commands==250,251,252,253,254,255
X@d id_byte=2 {identifies the kind of \.{DVI} files described here}
X
X@* Input from binary files.
XWe have seen that a \.{DVI} file is a sequence of 8-bit bytes. The bytes
Xappear physically in what is called a `|packed file of 0..255|'
Xin \PASCAL\ lingo.
X
XPacking is system dependent, and many \PASCAL\ systems fail to implement
Xsuch files in a sensible way (at least, from the viewpoint of producing
Xgood production software).  For example, some systems treat all
Xbyte-oriented files as text, looking for end-of-line marks and such
Xthings. Therefore some system-dependent code is often needed to deal with
Xbinary files, even though most of the program in this section of
X\.{DVIDOC} is written in standard \PASCAL.
X
XWe shall stick to simple \PASCAL\ in this program, for reasons of clarity,
Xeven if such simplicity is sometimes unrealistic.
X
X@<Types...@>=
X@!eight_bits=0..255; {unsigned one-byte quantity}
X@!byte_file=packed file of char; {files that contain binary data}
X
X@ The program deals with two binary file variables: |dvi_file| is the main
Xinput file that we are translating into symbolic form, and |tfm_file| is
Xthe current font metric file from which character-width information is
Xbeing read.
X
X@<Glob...@>=
X@!dvi_file:byte_file; {the stuff we are \.{DVI}typing}
X@!tfm_file:byte_file; {a font metric file}
X
X@ To prepare these files for input, we |reset| them. An extension of
X\PASCAL\ is needed in the case of |tfm_file|, since we want to associate
Xit with external files whose names are specified dynamically (i.e., not
Xknown at compile time). The following code assumes that `|reset(f,s)|'
Xdoes this, when |f| is a file variable and |s| is a string variable that
Xspecifies the file name. If |eof(f)| is true immediately after
X|reset(f,s)| has acted, we assume that no file named |s| is accessible.
X
X@d read_access_mode=4  {``read'' mode for |test_access|}
X@d write_access_mode=2 {``write'' mode for |test_access|}
X
X@d no_file_path=0    {no path searching should be done}
X@d font_file_path=3  {path specifier for \.{TFM} files}
X@p procedure open_dvi_file; {prepares to read packed bytes in |dvi_file|}
Xbegin
Xargv(1, cur_name);
Xif test_access(read_access_mode, no_file_path) then 
Xreset(dvi_file, real_name_of_file) else
Xbegin
Xerror('DVI file not found');
Xgoto done;
Xend;
Xcur_loc:=0;
Xend;
X@#
Xprocedure open_tfm_file; {prepares to read packed bytes in |tfm_file|}
Xbegin 
Xif test_access(read_access_mode, font_file_path) then 
Xreset(tfm_file, real_name_of_file) 
Xelse
Xbegin
Xerror('TFM file not found');
Xgoto done;
Xend;
Xend;
X
X@ If you looked carefully at the preceding code, you probably asked,
X``What are |cur_loc| and |cur_name|?'' Good question. They're global
Xvariables: |cur_loc| is the number of the byte about to be read next from
X|dvi_file|, and |cur_name| is a string variable that will be set to the
Xcurrent font metric file name before |open_tfm_file| is called.
X
X@<Glob...@>=
X@!cur_loc:integer; {where we are about to look, in |dvi_file|}
X@!cur_name,real_name_of_file:
Xpacked array[1..name_length] of char; {external name,
X  with no lower case letters}
X
X@ It turns out to be convenient to read four bytes at a time, when we are
Xinputting from \.{TFM} files. The input goes into global variables
X|b0|, |b1|, |b2|, and |b3|, with |b0| getting the first byte and |b3|
Xthe fourth.
X
X@<Glob...@>=
X@!b0,@!b1,@!b2,@!b3: eight_bits; {four bytes input at once}
X
X@ The |read_tfm_word| procedure sets |b0| through |b3| to the next
Xfour bytes in the current \.{TFM} file.
X@d get_tfm_byte(#) ==
X    read(tfm_file,byte); # := ord(byte);
X
X@p procedure read_tfm_word;
Xvar byte:char;
Xbegin
Xget_tfm_byte(b0);
Xget_tfm_byte(b1);
Xget_tfm_byte(b2);
Xget_tfm_byte(b3);
Xend;
X
X@ We shall use another set of simple functions to read the next byte or
Xbytes from |dvi_file|. There are seven possibilities, each of which is
Xtreated as a separate function in order to minimize the overhead for
Xsubroutine calls.
X
X@p function get_byte:integer; {returns the next byte, unsigned}
Xvar b:char;
Xbegin if eof(dvi_file) then get_byte:=0
Xelse  begin read(dvi_file,b); incr(cur_loc); get_byte:=ord(b);
X  end;
Xend;
X@#
Xfunction signed_byte:integer; {returns the next byte, signed}
Xvar b:char;
Xbegin read(dvi_file,b); incr(cur_loc);
Xif ord(b)<128 then signed_byte:=ord(b) @+ else signed_byte:=ord(b)-256;
Xend;
X@#
Xfunction get_two_bytes:integer; {returns the next two bytes, unsigned}
Xvar a,@!b:char;
Xbegin read(dvi_file,a); read(dvi_file,b);
Xcur_loc:=cur_loc+2;
Xget_two_bytes:=ord(a)*256+ord(b);
Xend;
X@#
Xfunction signed_pair:integer; {returns the next two bytes, signed}
Xvar a,@!b:char;
Xbegin read(dvi_file,a); read(dvi_file,b);
Xcur_loc:=cur_loc+2;
Xif ord(a)<128 then signed_pair:=ord(a)*256+ord(b)
Xelse signed_pair:=(ord(a)-256)*256+ord(b);
Xend;
X@#
Xfunction get_three_bytes:integer; {returns the next three bytes, unsigned}
Xvar a,@!b,@!c:char;
Xbegin read(dvi_file,a); read(dvi_file,b); read(dvi_file,c);
Xcur_loc:=cur_loc+3;
Xget_three_bytes:=(ord(a)*256+ord(b))*256+ord(c);
Xend;
X@#
Xfunction signed_trio:integer; {returns the next three bytes, signed}
Xvar a,@!b,@!c:char;
Xbegin read(dvi_file,a); read(dvi_file,b); read(dvi_file,c);
Xcur_loc:=cur_loc+3;
Xif ord(a)<128 then signed_trio:=(ord(a)*256+ord(b))*256+ord(c)
Xelse signed_trio:=((ord(a)-256)*256+ord(b))*256+ord(c);
Xend;
X@#
Xfunction signed_quad:integer; {returns the next four bytes, signed}
Xvar a,@!b,@!c,@!d:char;
Xbegin read(dvi_file,a); read(dvi_file,b); read(dvi_file,c); read(dvi_file,d);
Xcur_loc:=cur_loc+4;
Xif ord(a)<128 then signed_quad:=((ord(a)*256+ord(b))*256+ord(c))*256+ord(d)
Xelse signed_quad:=(((ord(a)-256)*256+ord(b))*256+ord(c))*256+ord(d);
Xend;
X
X@ Finally we come to the routines that do random file access.
XThe driver program below needs two such routines: |dvi_length| should
Xcompute the total number of bytes in |dvi_file|, possibly also
Xcausing |eof(dvi_file)| to be true; and |move_to_byte(n)|
Xshould position |dvi_file| so that the next |get_byte| will read byte |n|,
Xstarting with |n=0| for the first byte in the file.
X
X@p function dvi_length:integer;
Xvar i:integer;
X    j:char;
Xbegin 
Xreset(dvi_file);
Xi := 0;
Xwhile not eof(dvi_file) do
Xbegin
X    read(dvifile, j);
X    incr(i);
Xend;
Xcur_loc := i;
Xdvi_length := i;
Xend;
X@#
Xprocedure move_to_byte(n:integer);
Xvar i:integer;
X    j:char;
Xbegin 
Xreset(dvi_file);
Xi := 0;
Xwhile i < n do
Xbegin
X    read(dvi_file, j);
X    incr(i);
Xend;
Xcur_loc := n;
Xend;
X
X@* Reading the font information.
X\.{DVI} file format does not include information about character widths, since
Xthat would tend to make the files a lot longer. But a program that reads
Xa \.{DVI} file is supposed to know the widths of the characters that appear
Xin \\{set\_char} commands. Therefore \.{DVIDOC} looks at the font metric
X(\.{TFM}) files for the fonts that are involved.
X@.TFM {\rm files}@>
X
X@ For purposes of this program, we need to know only two things about a
Xgiven character |c| in a given font |f|: (1)@@Is |c| a legal character
Xin@@|f|? (2)@@If so, what is the width of |c|? We also need to know the
Xsymbolic name of each font, so it can be printed out, and we need to know
Xthe approximate size of inter-word spaces in each font.
X
XThe answers to these questions appear implicitly in the following data
Xstructures. The current number of known fonts is |nf|. Each known font has
Xan internal number |f|, where |0<=f<nf|; the external number of this font,
Xi.e., its font identification number in the \.{DVI} file, is
X|font_num[f]|, and the external name of this font is the string that
Xoccupies positions |font_name[f]| through |font_name[f+1]-1| of the array
X|names|. The latter array consists of |ascii_code| characters, and
X|font_name[nf]| is its first unoccupied position.  A horizontal motion
Xless than |font_space[f]| will be treated as a `kern'.
XThe
Xlegal characters run from |font_bc[f]| to |font_ec[f]|, inclusive; more
Xprecisely, a given character |c| is valid in font |f| if and only if
X|font_bc[f]<=c<=font_ec[f]| and |char_width(f)(c)<>invalid_width|.
X(Exception: If |font_ec[f]=256|, all characters |c>=256| are valid and have
Xthe same width |char_width(f)(256)|.)
X@^oriental characters@>@^Chinese characters@>@^Japanese characters@>
XFinally, |char_width(f)(c)=width[width_base[f]+c]|, and |width_ptr| is the
Xfirst unused position of the |width| array.
X
X@d char_width_end(#)==#]
X@d char_width(#)==width[width_base[#]+char_width_end
X@d invalid_width==@'17777777777
X
X@<Glob...@>=
X@!font_num:array [0..max_fonts] of integer; {external font numbers}
X@!font_name:array [0..max_fonts] of 0..name_size; {starting positions
X  of external font names}
X@!names:array [0..name_size] of ascii_code; {characters of names}
X@!font_check_sum:array [0..max_fonts] of integer; {check sums}
X@!font_scaled_size:array [0..max_fonts] of integer; {scale factors}
X@!font_design_size:array [0..max_fonts] of integer; {design sizes}
X@!font_space:array [0..max_fonts] of integer; {boundary between ``small''
X  and ``large'' spaces}
X@!font_bc:array [0..max_fonts] of integer; {beginning characters in fonts}
X@!font_ec:array [0..max_fonts] of integer; {ending characters in fonts}
X@!width_base:array [0..max_fonts] of integer; {index into |width| table}
X@!width:array [0..max_widths] of integer; {character widths, in \.{DVI} units}
X@!nf:0..max_fonts; {the number of known fonts}
X@!width_ptr:0..max_widths; {the number of known character widths}
X
X@ @<Set init...@>=
Xnf:=0; width_ptr:=0; font_name[0]:=0;
X
X@ It is, of course, a simple matter to print the name of a given font.
X
X@p procedure print_font(@!f:integer); {|f| is an internal font number}
Xvar k:0..name_size; {index into |names|}
Xbegin if f=nf then write(term_out,'UNDEFINED!')
X@.UNDEFINED@>
Xelse  begin for k:=font_name[f] to font_name[f+1]-1 do
X    write(term_out,xchr[names[k]]);
X  end;
Xend;
X
X@ An auxiliary array |in_width| is used to hold the widths as they are
Xinput. The global variable |tfm_check_sum| is set to the check sum that
Xappears in the current \.{TFM} file.
X
X@<Glob...@>=
X@!in_width:array[0..255] of integer; {\.{TFM} width data in \.{DVI} units}
X@!tfm_check_sum:integer; {check sum found in |tfm_file|}
X
X@ Here is a procedure that absorbs the necessary information from a
X\.{TFM} file, assuming that the file has just been successfully reset
Xso that we are ready to read its first byte. (A complete description of
X\.{TFM} file format appears in the documentation of \.{TFtoPL} and will
Xnot be repeated here.) The procedure does not check the \.{TFM} file
Xfor validity, nor does it give explicit information about what is
Xwrong with a \.{TFM} file that proves to be invalid; \.{DVI}-reading
Xprograms need not do this, since \.{TFM} files are almost always valid,
Xand since the \.{TFtoPL} utility program has been specifically designed
Xto diagnose \.{TFM} errors. The procedure simply returns |false| if it
Xdetects anything amiss in the \.{TFM} data.
X
XThere is a parameter, |z|, which represents the scaling factor being
Xused to compute the font dimensions; it must be in the range $0<z<2^{27}$.
X
X@p function in_TFM(@!z:integer):boolean; {input \.{TFM} data or return |false|}
Xlabel 9997, {go here when the format is bad}
X  9998,  {go here when the information cannot be loaded}
X  9999;  {go here to exit}
Xvar k:integer; {index for loops}
X@!lh:integer; {length of the header data, in four-byte words}
X@!nw:integer; {number of words in the width table}
X@!wp:0..max_widths; {new value of |width_ptr| after successful input}
X@!alpha,@!beta:integer; {quantities used in the scaling computation}
Xbegin @<Read past the header data; |goto 9997| if there is a problem@>;
X@<Store character-width indices at the end of the |width| table@>;
X@<Read and convert the width values, setting up the |in_width| table@>;
X@<Move the widths from |in_width| to |width|, and append |pixel_width| values@>;
Xwidth_ptr:=wp; in_TFM:=true; goto 9999;
X9997: write_ln(term_out,'---not loaded, TFM file is bad');
X@.TFM file is bad@>
X9998: in_TFM:=false;
X9999: end;
X
X@ @<Read past the header...@>=
Xread_tfm_word; lh:=b2*256+b3;
Xread_tfm_word; font_bc[nf]:=b0*256+b1; font_ec[nf]:=b2*256+b3;
Xif font_ec[nf]<font_bc[nf] then font_bc[nf]:=font_ec[nf]+1;
Xif width_ptr+font_ec[nf]-font_bc[nf]+1>max_widths then
X  begin write_ln(term_out,'---not loaded, DVIDOC needs larger width table');
X@.DVIDOC needs larger...@>
X    goto 9998;
X  end;
Xwp:=width_ptr+font_ec[nf]-font_bc[nf]+1;
Xread_tfm_word; nw:=b0*256+b1;
Xif (nw=0)or(nw>256) then goto 9997;
Xfor k:=1 to 3+lh do
X  begin if eof(tfm_file) then goto 9997;
X  read_tfm_word;
X  if k=4 then
X    if b0<128 then tfm_check_sum:=((b0*256+b1)*256+b2)*256+b3
X    else tfm_check_sum:=(((b0-256)*256+b1)*256+b2)*256+b3;
X  end;
X
X@ @<Store character-width indices...@>=
Xif wp>0 then for k:=width_ptr to wp-1 do
X  begin read_tfm_word;
X  if b0>nw then goto 9997;
X  width[k]:=b0;
X  end;
X
X@ The most important part of |in_TFM| is the width computation, which
Xinvolves multiplying the relative widths in the \.{TFM} file by the
Xscaling factor in the \.{DVI} file. This fixed-point multiplication
Xmust be done with precisely the same accuracy by all \.{DVI}-reading programs,
Xin order to validate the assumptions made by \.{DVI}-writing programs
Xlike \TeX82.
X
XLet us therefore summarize what needs to be done. Each width in a \.{TFM}
Xfile appears as a four-byte quantity called a |fix_word|.  A |fix_word|
Xwhose respective bytes are $(a,b,c,d)$ represents the number
X$$x=\left\{\vcenter{\halign{$#$,\hfil\qquad&if $#$\hfil\cr
Xb\cdot2^{-4}+c\cdot2^{-12}+d\cdot2^{-20}&a=0;\cr
X-16+b\cdot2^{-4}+c\cdot2^{-12}+d\cdot2^{-20}&a=255.\cr}}\right.$$
X(No other choices of $a$ are allowed, since the magnitude of a \.{TFM}
Xdimension must be less than 16.)  We want to multiply this quantity by the
Xinteger@@|z|, which is known to be less then $2^{27}$. Let $\alpha=16z$.
XIf $|z|<2^{23}$, the individual multiplications $b\cdot z$, $c\cdot z$,
X$d\cdot z$ cannot overflow; otherwise we will divide |z| by 2, 4, 8, or
X16, to obtain a multiplier less than $2^{23}$, and we can compensate for
Xthis later. If |z| has thereby been replaced by $|z|^\prime=|z|/2^e$, let
X$\beta=2^{4-e}$; we shall compute
X$$\lfloor(b+c\cdot2^{-8}+d\cdot2^{-16})\,z^\prime/\beta\rfloor$$ if $a=0$,
Xor the same quantity minus $\alpha$ if $a=255$.  This calculation must be
Xdone exactly, for the reasons stated above; the following program does the
Xjob in a system-independent way, assuming that arithmetic is exact on
Xnumbers less than $2^{31}$ in magnitude.
X
X@<Read and convert the width values...@>=
X@<Replace |z| by $|z|^\prime$ and compute $\alpha,\beta$@>;
Xfor k:=0 to nw-1 do
X  begin read_tfm_word;
X  in_width[k]:=(((((b3*z)div@'400)+(b2*z))div@'400)+(b1*z))div beta;
X  if b0>0 then if b0<255 then goto 9997
X    else in_width[k]:=in_width[k]-alpha;
X  end
X
X@ @<Replace |z|...@>=
Xbegin alpha:=16*z; beta:=16;
Xwhile z>=@'40000000 do
X  begin z:=z div 2; beta:=beta div 2;
X  end;
Xend
X
X@ A \.{DVI}-reading program usually works with font files instead of
X\.{TFM} files, so \.{DVIDOC} is atypical in that respect. Font files
Xshould, however, contain exactly the same character width data that is
Xfound in the corresponding \.{TFM}s. In addition, font files usually
Xalso contain the widths of characters in pixels, since the device-independent
Xcharacter widths of \.{TFM} files are generally not perfect multiples of
Xpixels.
X
XThe |pixel_width| array contains this information; when |width[k]| is the
Xdevice-independent width of some character in \.{DVI} units, |pixel_width[k]|
Xis the corresponding width of that character in an actual font.
XThe macro |char_pixel_width| is set up to be analogous to |char_width|.
X
X@d char_pixel_width(#)==pixel_width[width_base[#]+char_width_end
X
X@<Glob...@>=
X@!pixel_width:array[0..max_widths] of integer; {actual character widths,
X  in pixels}
X@!horiz_conv:real; {converts \.{DVI} units to horizontal pixels}
X@!vert_conv:real; {converts \.{DVI} units to vertical pixels}
X@!true_horiz_conv:real; {converts unmagnified \.{DVI} units to pixels}
X@!true_vert_conv:real; {converts unmagnified \.{DVI} units to pixels}
X@!numerator,@!denominator:integer; {stated conversion ratio}
X@!mag:integer; {magnification factor times 1000}
X
X@ The following code computes pixel widths by simply rounding the \.{TFM}
Xwidths to the nearest integer number of pixels, based on the conversion factor
X|horiz_conv| that converts \.{DVI} units to pixels. 
X
X@d horiz_pixel_round(#)==trunc(horiz_conv*(#)+0.5)
X@d vert_pixel_round(#)==trunc(vert_conv*(#)+0.5)
X
X@<Move the widths from |in_width| to |width|, and append |pixel_width| values@>=
Xwidth_base[nf]:=width_ptr-font_bc[nf];
Xif wp>0 then for k:=width_ptr to wp-1 do
X  begin width[k]:=in_width[width[k]];
X  pixel_width[k]:=horiz_pixel_round(width[k]);
X  end
X
X@* Optional modes of output.

-- 
		Scott Simpson
		TRW Electronics and Defense Sector
		...{decvax,ihnp4,ucbvax}!trwrb!simpson

simpson@trwrb.UUCP (Scott Simpson) (09/10/86)

X\.{DVIDOC} output will vary depending on some
Xoptions that the user must specify: The typeout can be confined to a
Xrestricted subset of the pages by specifying the desired starting page and
Xthe maximum number of pages. Furthermore there is an option to specify the
Xhorizontal and vertical
Xresolution of the printer or display; and there is an option to override the
Xmagnification factor that is stated in the \.{DVI} file.
X
XThe starting page is specified by giving a sequence of 1 to 10 numbers or
Xasterisks separated by dots. For example, the specification `\.{1.*.-5}'
Xcan be used to refer to a page output by \TeX\ when $\.{\\count0}=1$
Xand $\.{\\count2}=-5$. (Recall that |bop| commands in a \.{DVI} file
Xare followed by ten `count' values.) An asterisk matches any number,
Xso the `\.*' in `\.{1.*.-5}' means that \.{\\count1} is ignored when
Xspecifying the first page. If several pages match the given specification,
X\.{DVIDOC} will begin with the earliest such page in the file. The
Xdefault specification `\.*' (which matches all pages) therefore denotes
Xthe page at the beginning of the file.
X
XWhen \.{DVIDOC} begins, it engages the user in a brief dialog so that the
Xoptions will be specified. This part of \.{DVIDOC} requires nonstandard
X\PASCAL\ constructions to handle the online interaction.
X
X@<Glob...@>=
X@!max_pages:integer; {at most this many |bop..eop| pages will be printed}
X@!horiz_resolution:real; {pixels per inch}
X@!vert_resolution:real; {pixels per inch}
X@!new_mag:integer; {if positive, overrides the postamble's magnification}
X
X@ The starting page specification is recorded in two global arrays called
X|start_count| and |start_there|. For example, `\.{1.*.-5}' is represented
Xby |start_there[0]=true|, |start_count[0]=1|, |start_there[1]=false|,
X|start_there[2]=true|, |start_count[2]=-5|.
XWe also set |start_vals=2|, to indicate that count 2 was the last one
Xmentioned. The other values of |start_count| and |start_there| are not
Ximportant, in this example.
X
X@<Glob...@>=
X@!start_count:array[0..9] of integer; {count values to select starting page}
X@!start_there:array[0..9] of boolean; {is the |start_count| value relevant?}
X@!start_vals:0..9; {the last count considered significant}
X@!count:array[0..9] of integer; {the count values on the current page}
X
X@ @<Set init...@>=
Xmax_pages:=1000000; start_vals:=0; start_there[0]:=false;
X
X@ Here is a simple subroutine that tests if the current page might be the
Xstarting page.
X
X@p function start_match:boolean; {does |count| match the starting spec?}
Xvar k:0..9;  {loop index}
X@!match:boolean; {does everything match so far?}
Xbegin match:=true;
Xfor k:=0 to start_vals do
X  if start_there[k]and(start_count[k]<>count[k]) then match:=false;
Xstart_match:=match;
Xend;
X
X@ The |input_ln| routine waits for the user to type a line at his or her
Xterminal; then it puts ascii-code equivalents for the characters on that line
Xinto the |buffer| array. 
X
X@<Glob...@>=
X@!buffer:array[0..terminal_line_length] of ascii_code;
X
X@ Since the terminal is being used for both input and output, some systems
Xneed a special routine to make sure that the user can see a prompt message
Xbefore waiting for input based on that message. (Otherwise the message
Xmay just be sitting in a hidden buffer somewhere, and the user will have
Xno idea what the program is waiting for.) We shall call a system-dependent
Xsubroutine |update_terminal| in order to avoid this problem.
X
X@d update_terminal == flush(term_out) {empty the terminal output buffer}
X
X@ During the dialog, \.{DVIDOC} will treat the first blank space in a
Xline as the end of that line. Therefore |input_ln| makes sure that there
Xis always at least one blank space in |buffer|.
X
X@p procedure input_ln; {inputs a line from the terminal}
Xvar k:0..terminal_line_length;
Xbegin update_terminal;
Xif eoln(term_in) then read_ln(term_in);
Xk:=0;
Xwhile (k<terminal_line_length)and not eoln(term_in) do
X  begin buffer[k]:=xord[term_in^]; incr(k); get(term_in);
X  end;
Xbuffer[k]:=" ";
Xend;
X
X@ The global variable |buf_ptr| is used while scanning each line of input;
Xit points to the first unread character in |buffer|.
X
X@<Glob...@>=
X@!buf_ptr:0..terminal_line_length; {the number of characters read}
X
X@ Here is a routine that scans a (possibly signed) integer and computes
Xthe decimal value. If no decimal integer starts at |buf_ptr|, the
Xvalue 0 is returned. The integer should be less than $2^{31}$ in
Xabsolute value.
X
X@p function get_integer:integer;
Xvar x:integer; {accumulates the value}
X@!negative:boolean; {should the value be negated?}
Xbegin if buffer[buf_ptr]="-" then
X  begin negative:=true; incr(buf_ptr);
X  end
Xelse negative:=false;
Xx:=0;
Xwhile (buffer[buf_ptr]>="0")and(buffer[buf_ptr]<="9") do
X  begin x:=10*x+buffer[buf_ptr]-"0"; incr(buf_ptr);
X  end;
Xif negative then get_integer:=-x @+ else get_integer:=x;
Xend;
X
X@ The selected options are put into global variables by the |dialog|
Xprocedure, which is called just as \.{DVIDOC} begins.
X
X@p procedure dialog;
Xlabel 1,2,3,4,5;
Xvar k:integer; {loop variable}
Xbegin
Xwrite_ln(term_out,banner);
X@<Determine the desired |start_count| values@>;
X@<Determine the desired |max_pages|@>;
X@<Determine the desired |horiz_resolution|@>;
X@<Determine the desired |vert_resolution|@>;
X@<Determine the desired |new_mag|@>;
Xend;
X
X@ @<Determine the desired |start...@>=
X2: write(term_out,'Starting page (default=*): ');
Xstart_vals:=0; start_there[0]:=false;
Xinput_ln; buf_ptr:=0; k:=0;
Xif buffer[0]<>" " then
X  repeat if buffer[buf_ptr]="*" then
X    begin start_there[k]:=false; incr(buf_ptr);
X    end
X  else  begin start_there[k]:=true; start_count[k]:=get_integer;
X    end;
X  if (k<9)and(buffer[buf_ptr]=".") then
X    begin incr(k); incr(buf_ptr);
X    end
X  else if buffer[buf_ptr]=" " then start_vals:=k
X  else  begin write(term_out,'Type, e.g., 1.*.-5 to specify the ');
X    write_ln(term_out,'first page with \count0=1, \count2=-5.');
X    goto 2;
X    end;
X  until start_vals=k
X
X@ @<Determine the desired |max_pages|@>=
X3: write(term_out,'Maximum number of pages (default=1000000): ');
Xmax_pages:=1000000; input_ln; buf_ptr:=0;
Xif buffer[0]<>" " then
X  begin max_pages:=get_integer;
X  if max_pages<=0 then
X    begin write_ln(term_out,'Please type a positive number.');
X    goto 3;
X    end;
X  end
X
X@ @<Determine the desired |horiz_resolution|@>=
X1: write(term_out,'Horizontal resolution');
Xwrite(term_out,' in characters per inch (default=10/1): ');
Xhoriz_resolution:=10.0; input_ln; buf_ptr:=0;
Xif buffer[0]<>" " then
X  begin k:=get_integer;
X  if (k>0)and(buffer[buf_ptr]="/")and
X    (buffer[buf_ptr+1]>"0")and(buffer[buf_ptr+1]<="9") then
X    begin incr(buf_ptr); horiz_resolution:=k/get_integer;
X    end
X  else  begin write(term_out,'Type a ratio of positive integers;');
X    write_ln(term_out,' (1 character per mm would be 254/10).');
X    goto 1;
X    end;
X  end
X
X@ @<Determine the desired |vert_resolution|@>=
X4: write(term_out,'Vertical resolution');
Xwrite(term_out,' in lines per inch (default=6/1): ');
Xvert_resolution:=6.0; input_ln; buf_ptr:=0;
Xif buffer[0]<>" " then
X  begin k:=get_integer;
X  if (k>0)and(buffer[buf_ptr]="/")and
X    (buffer[buf_ptr+1]>"0")and(buffer[buf_ptr+1]<="9") then
X    begin incr(buf_ptr); vert_resolution:=k/get_integer;
X    end
X  else  begin write(term_out,'Type a ratio of positive integers;');
X    write_ln(term_out,' (1 line per mm would be 254/10).');
X    goto 4;
X    end;
X  end
X
X@ @<Determine the desired |new_mag|@>=
X5: write(term_out,'New magnification (default=0 to keep the old one): ');
Xnew_mag:=0; input_ln; buf_ptr:=0;
Xif buffer[0]<>" " then
X  if (buffer[0]>="0")and(buffer[0]<="9") then new_mag:=get_integer
X  else  begin write(term_out,'Type a positive integer to override ');
X    write_ln(term_out,'the magnification in the DVI file.');
X    goto 5;
X    end
X
X@* Defining fonts.
X\.{DVIDOC} reads the postamble first and loads
Xall of the donts defined there; then it processes the pages. In this
Xcase, a \\{fnt\_def} command should match a previous definition if and only
Xif the \\{fnt\_def} being processed is not in the postamble. 
X
XA global variable |in_postamble| is provided to tell whether we are
Xprocessing the postamble or not.
X
X@<Glob...@>=
X@!in_postamble:boolean; {are we reading the postamble?}
X
X@ @<Set init...@>=
Xin_postamble:=false;
X
X@ The following subroutine does the necessary things when a \\{fnt\_def}
Xcommand is being processed.
X
X@p procedure define_font(@!e:integer); {|e| is an external font number}
Xvar f:0..max_fonts;
X@!p:integer; {length of the area/directory spec}
X@!n:integer; {length of the font name proper}
X@!c,@!q,@!d:integer; {check sum, scaled size, and design size}
X@!r:0..name_length; {index into |cur_name|}
X@!j,@!k:0..name_size; {indices into |names|}
X@!mismatch:boolean; {do names disagree?}
Xbegin if nf=max_fonts then abort('DVIDOC capacity exceeded (max fonts=',
X    max_fonts:0,')!');
X@.DVIDOC capacity exceeded...@>
Xfont_num[nf]:=e; f:=0;
Xwhile font_num[f]<>e do incr(f);
X@<Read the font parameters into position for font |nf|, and
X  print the font name@>;
Xif in_postamble then
X  begin if f<nf then write_ln(term_out,'---this font was already defined!');
X@.this font was already defined@>
X  end
Xelse  begin if f=nf then write_ln(term_out,'---this font wasn''t loaded before!');
X@.this font wasn't loaded before@>
X  end;
Xif f=nf then @<Load the new font, unless there are problems@>
Xelse @<Check that the current font definition matches the old one@>;
Xend;
X
X@ @<Check that the current...@>=
Xbegin if font_check_sum[f]<>c then
X  write_ln(term_out,'---check sum doesn''t match previous definition!');
X@.check sum doesn't match@>
Xif font_scaled_size[f]<>q then
X  write_ln(term_out,'---scaled size doesn''t match previous definition!');
X@.scaled size doesn't match@>
Xif font_design_size[f]<>d then
X  write_ln(term_out,'---design size doesn''t match previous definition!');
X@.design size doesn't match@>
Xj:=font_name[f]; k:=font_name[nf]; mismatch:=false;
Xwhile j<font_name[f+1] do
X  begin if names[j]<>names[k] then mismatch:=true;
X  incr(j); incr(k);
X  end;
Xif k<>font_name[nf+1] then mismatch:=true;
Xif mismatch then write_ln(term_out,'---font name doesn''t match previous definition!');
X@.font name doesn't match@>
Xwrite_ln(term_out)
Xend
X
X@ @<Read the font parameters into position for font |nf|...@>=
Xc:=signed_quad; font_check_sum[nf]:=c;@/
Xq:=signed_quad; font_scaled_size[nf]:=q;@/
Xd:=signed_quad; font_design_size[nf]:=d;@/
Xp:=get_byte; n:=get_byte;
Xif font_name[nf]+n+p>name_size then
X  abort('DVIDOC capacity exceeded (name size=',name_size:0,')!');
X@.DVIDOC capacity exceeded...@>
Xfont_name[nf+1]:=font_name[nf]+n+p;
Xwrite(term_out,'Font ',e:0,': ');
Xif n+p=0 then write(term_out,'null font name!')
X@.null font name@>
Xelse for k:=font_name[nf] to font_name[nf+1]-1 do names[k]:=get_byte;
Xincr(nf); print_font(nf-1); decr(nf)
X
X@ @<Load the new font, unless there are problems@>=
Xbegin @<Move font name into the |cur_name| string@>;
Xopen_tfm_file;
Xif eof(tfm_file) then
X  write(term_out,'---not loaded, TFM file can''t be opened!')
X@.TFM file can\'t be opened@>
Xelse  begin if (q<=0)or(q>=@'1000000000) then
X    write(term_out,'---not loaded, bad scale (',q:0,')!')
X@.bad scale@>
X  else if (d<=0)or(d>=@'1000000000) then
X    write(term_out,'---not loaded, bad design size (',d:0,')!')
X@.bad design size@>
X  else if in_TFM(q) then @<Finish loading the new font info@>;
X  end;
Xwrite_ln(term_out,' ');
Xend
X
X@ @<Finish loading...@>=
Xbegin font_space[nf]:=q div 6; {this is a 3-unit ``thin space''}
Xif (c<>0)and(tfm_check_sum<>0)and(c<>tfm_check_sum) then
X  begin write_ln(term_out,'---beware: check sums do not agree!');
X@.beware: check sums do not agree@>
X@.check sums do not agree@>
X  write_ln(term_out,'   (',c:0,' vs. ',tfm_check_sum:0,')');
X  write(term_out,'   ');
X  end;
Xwrite(term_out,'---loaded at size ',q:0,' DVI units');
Xd:=trunc((100.0*horiz_conv*q)/(true_horiz_conv*d)+0.5);
Xif d<>100 then
X  begin write_ln(term_out,' '); write(term_out,' (this font is magnified ',d:0,'%)');
X  end;
X@.this font is magnified@>
Xincr(nf); {now the new font is officially present}
Xend
X
X@ If |p=0|, i.e., if no font directory has been specified, \.{DVIDOC}
Xis supposed to use the default font directory, which is a
Xsystem-dependent place where the standard fonts are kept.
XThe string variable |default_directory| contains the name of this area.
X@^changed module@>
X
X@d default_directory_name=='TEXFONTS:' {changed to the correct name}
X@d default_directory_name_length=9 {changed to the correct length}
X
X@<Glob...@>=
X@!default_directory:packed array[1..default_directory_name_length] of char;
X
X@ @<Set init...@>=
Xdefault_directory:=default_directory_name;
X
X@ The string |cur_name| is supposed to be set to the external name of the
X\.{TFM} file for the current font. This usually means that we need to,
Xat most sites, append the
Xsuffix ``.tfm''.
X
X@<Move font name into the |cur_name| string@>=
Xfor k:=1 to name_length do cur_name[k]:=' ';
Xr:=0;
Xfor k:=font_name[nf] to font_name[nf+1]-1 do
X  begin incr(r);
X  if r+4>name_length then
X    abort('DVIDOC capacity exceeded (max font name length=',
X      name_length:0,')!');
X@.DVIDOC capacity exceeded...@>
X    cur_name[r]:=xchr[names[k]];
X    end;
Xcur_name[r+1]:='.'; cur_name[r+2]:='t'; cur_name[r+3]:='f'; cur_name[r+4]:='m'
X
X@* Low level output routines.
XCharacters set by the \.{DVI} file are placed in |page_buffer|, a two
Xdimensional array of characters with one element for each print
Xposition on the page.  The |page_buffer| is cleared at the beginning
Xof each page and printed at the end of each page.  
X|doc_file|, the file to which the document is destined, is an ordinary text
Xfile.
X
XTo optimize the initialization and printing of |page_buffer|, a high
Xwater mark line number, |page_hwm|, is kept to indicate the last line
Xthat contains any printable characters, and for each line a high water
Xmark character number, |line_hwm|, is kept to indicate the location of
Xthe last printable character in the line.
X
X@<Glob...@>=
X@!doc_file:text_file;
X@!page_buffer:packed array[1..page_width_max,1..page_length_max] of ascii_code;
X                 {storage for a document page}
X@!line_hwm:array[1..page_length_max] of 0..page_width_max;
X                 {high water marks for each line}
X@!page_hwm: 0..page_length_max;  {high water mark for page}
X
X@ |doc_file| needs to be opened.
X
X@<Set initial values@>=
Xargv(2, cur_name);
Xif test_access(write_access_mode, no_file_path) then
Xrewrite(doc_file, cur_name)
Xelse begin
Xerror('Cannot write output file');
Xgoto done;
Xend;
X
X@ The |flush_page| procedure will print the |page_buffer|.
X
X@p procedure flush_page;
Xvar i:0..page_width_max; j:0..page_length_max;
Xbegin
X  for j := 1 to page_hwm do begin
X    for i := 1 to line_hwm[j] do
X      write (doc_file, xchr[page_buffer[i,j]]);
X    write_ln (doc_file) end;
X  write (doc_file, chr(12))  {end the page with a form feed}  
Xend;
X
X@ The |empty_page| procedure will empty the |page_buffer| data structure.
X
X@p procedure empty_page;
Xbegin page_hwm := 0 end;
X
X@ And the |out_char| procedure puts something into it.  The usual printable
Xascii characters will be put into the buffer as is.  Non-printable characters,
Xincluding the blank, will be put into the buffer as question mark chracters.
X
X@p procedure out_char(p,hh,vv:integer);
Xvar i:1..page_width_max; j:1..page_length_max;
X     {|hh| and |vv| range from zero up while |i| and |j| range from one up.}
X    k: integer;
X    c: ascii_code;
Xbegin
X  if 
X    (p>" ")and(p<="~") then c:=p
X    else c:=xord['?'];
X  if 
X    (hh>page_width_max-1) or (vv>page_length_max-1) then begin 
X      write_ln (term_out);
X      write (term_out, 'Character "', xchr[c], '" set at column ', hh+1:0);
X      write_ln (term_out, ' and row ', vv+1:0, ',');
X      write (term_out, 'outside the range of DVIDOC (');
X@.outside the range of DVIDOC@>
X      write (term_out, page_width_max:0, ',', page_length_max:0, ').');
X      write_ln (term_out) end
X    else begin
X      i := hh + 1;
X      j := vv + 1;
X      if j>page_hwm then begin {initialize any as yet untouched lines}
X        for k := page_hwm+1 to j do line_hwm[k]:=0;
X        page_hwm := j end;
X      if i>line_hwm[j] then begin {initialize any as yet untouched characters}
X        for k := line_hwm[j]+1 to i do page_buffer[k,j] := xord[' '];
X        line_hwm[j] := i end;
X      page_buffer[i,j] := c {put the character in its place}  end
Xend;
X
X@* Translation to symbolic form.
XThe main work of \.{DVIDOC} is accomplished by the |do_page| procedure,
Xwhich produces the output for an entire page, assuming that the |bop|
Xcommand for that page has already been processed. This procedure is
Xessentially an interpretive routine that reads and acts on the \.{DVI}
Xcommands.
X
X@ The definition of \.{DVI} files refers to six registers,
X$(h,v,w,x,y,z)$, which hold integer values in \.{DVI} units.  In practice,
Xwe also need registers |hh| and |vv|, the pixel analogs of $h$ and $v$,
Xsince it is not always true that |hh=horiz_pixel_round(h)| or
X|vv=vert_pixel_round(v)|.
X
XThe stack of $(h,v,w,x,y,z)$ values is represented by eight arrays
Xcalled |hstack|, \dots, |zstack|, |hhstack|, and |vvstack|.
X
X@<Glob...@>=
X@!h,@!v,@!w,@!x,@!y,@!z,@!hh,@!vv:integer; {current state values}
X@!hstack,@!vstack,@!wstack,@!xstack,@!ystack,@!zstack:
X  array [0..stack_size] of integer; {pushed down values in \.{DVI} units}
X@!hhstack,@!vvstack:
X  array [0..stack_size] of integer; {pushed down values in pixels}
X
X@ Three characteristics of the pages (their |max_v|, |max_h|, and
X|max_s|) are specified in the postamble, and a warning message
Xis printed if these limits are exceeded. Actually |max_v| is set to
Xthe maximum height plus depth of a page, and |max_h| to the maximum width,
Xfor purposes of page layout. Since characters can legally be set outside
Xof the page boundaries, it is not an error when |max_v| or |max_h| is
Xexceeded. But |max_s| should not be exceeded.
X
XThe postamble also specifies the total number of pages; \.{DVIDOC}
Xchecks to see if this total is accurate.
X
X@<Glob...@>=
X@!max_v:integer; {the value of |abs(v)| should probably not exceed this}
X@!max_h:integer; {the value of |abs(h)| should probably not exceed this}
X@!max_s:integer; {the stack depth should not exceed this}
X@!max_v_so_far,@!max_h_so_far,@!max_s_so_far:integer; {the record high levels}
X@!total_pages:integer; {the stated total number of pages}
X@!page_count:integer; {the total number of pages seen so far}
X
X@ @<Set init...@>=
Xmax_v:=@'17777777777; max_h:=@'17777777777; max_s:=stack_size+1;@/
Xmax_v_so_far:=0; max_h_so_far:=0; max_s_so_far:=0; page_count:=0;
X
X@ Before we get into the details of |do_page|, it is convenient to
Xconsider a simpler routine that computes the first parameter of each
Xopcode.
X
X@d four_cases(#)==#,#+1,#+2,#+3
X@d eight_cases(#)==four_cases(#),four_cases(#+4)
X@d sixteen_cases(#)==eight_cases(#),eight_cases(#+8)
X@d thirty_two_cases(#)==sixteen_cases(#),sixteen_cases(#+16)
X@d sixty_four_cases(#)==thirty_two_cases(#),thirty_two_cases(#+32)
X
X@p function first_par(o:eight_bits):integer;
Xbegin case o of
Xsixty_four_cases(set_char_0),sixty_four_cases(set_char_0+64):
X  first_par:=o-set_char_0;
Xset1,put1,fnt1,xxx1,fnt_def1: first_par:=get_byte;
Xset1+1,put1+1,fnt1+1,xxx1+1,fnt_def1+1: first_par:=get_two_bytes;
Xset1+2,put1+2,fnt1+2,xxx1+2,fnt_def1+2: first_par:=get_three_bytes;
Xright1,w1,x1,down1,y1,z1: first_par:=signed_byte;
Xright1+1,w1+1,x1+1,down1+1,y1+1,z1+1: first_par:=signed_pair;
Xright1+2,w1+2,x1+2,down1+2,y1+2,z1+2: first_par:=signed_trio;
Xset1+3,set_rule,put1+3,put_rule,right1+3,w1+3,x1+3,down1+3,y1+3,z1+3,
X  fnt1+3,xxx1+3,fnt_def1+3: first_par:=signed_quad;
Xnop,bop,eop,push,pop,pre,post,post_post,undefined_commands: first_par:=0;
Xw0: first_par:=w;
Xx0: first_par:=x;
Xy0: first_par:=y;
Xz0: first_par:=z;
Xsixty_four_cases(fnt_num_0): first_par:=o-fnt_num_0;
Xend;
Xend;
X
X@ Here are two other subroutines that we need: They compute the number of
Xpixels in the height or width of a rule. Characters and rules will line up
Xproperly if the sizes are computed precisely as specified here.  (Since
X|horiz_conv| and |vert_conv| 
Xare computed with some floating-point roundoff error, in a
Xmachine-dependent way, format designers who are tailoring something for a
Xparticular resolution should not plan their measurements to come out to an
Xexact integer number of pixels; they should compute things so that the
Xrule dimensions are a little less than an integer number of pixels, e.g.,
X4.99 instead of 5.00.)
X
X@p function horiz_rule_pixels(x:integer):integer;
X  {computes $\lceil|horiz_conv|\cdot x\rceil$}
Xvar n:integer;
Xbegin n:=trunc(horiz_conv*x);
Xif n<horiz_conv*x then horiz_rule_pixels:=n+1 @+ else horiz_rule_pixels:=n;
Xend;
X
Xfunction vert_rule_pixels(x:integer):integer;
X  {computes $\lceil|vert_conv|\cdot x\rceil$}
Xvar n:integer;
Xbegin n:=trunc(vert_conv*x);
Xif n<vert_conv*x then vert_rule_pixels:=n+1 @+ else vert_rule_pixels:=n;
Xend;
X
X@ Strictly speaking, the |do_page| procedure is really a function with
Xside effects, not a `\&{procedure}'; it returns the value |false| if
X\.{DVIDOC} should be aborted because of some unusual happening. The
Xsubroutine is organized as a typical interpreter, with a multiway branch
Xon the command code followed by |goto| statements leading to routines that
Xfinish up the activities common to different commands. We will use the
Xfollowing labels:
X
X@d fin_set=41 {label for commands that set or put a character}
X@d fin_rule=42 {label for commands that set or put a rule}
X@d move_right=43 {label for commands that change |h|}
X@d move_down=44 {label for commands that change |v|}
X@d show_state=45 {label for commands that change |s|}
X@d change_font=46 {label for commands that change |cur_font|}
X
X@ Some \PASCAL\ compilers severely restrict the length of procedure bodies,
Xso we shall split |do_page| into two parts, one of which is
Xcalled |special_cases|. The different parts communicate with each other
Xvia the global variables mentioned above, together with the following ones:
X
X@<Glob...@>=
X@!s:integer; {current stack size}
X@!ss:integer; {stack size to print}
X@!cur_font:integer; {current internal font number}
X
X@ Here is the overall setup.
X
X@p @<Declare the function called |special_cases|@>@;
Xfunction do_page:boolean;
Xlabel fin_set,fin_rule,move_right,show_state,done,9998,9999;
Xvar o:eight_bits; {operation code of the current command}
X@!p,@!q:integer; {parameters of the current command}
X@!a:integer; {byte number of the current command}
Xi,j:integer; {for loop indices for setting rules}
Xbegin empty_page; cur_font:=nf; {set current font undefined}
Xs:=0; h:=0; v:=0; w:=0; x:=0; y:=0; z:=0; hh:=0; vv:=0;
X  {initialize the state variables}
Xwhile true do @<Translate the next command in the \.{DVI} file;
X    |goto 9999| with |do_page=true| if it was |eop|;
X    |goto 9998| if premature termination is needed@>;
X9998: write_ln(term_out,'!'); do_page:=false;
X9999: end;
X
X@ 
X
X@<Translate the next command...@>=
Xbegin a:=cur_loc; 
Xo:=get_byte; p:=first_par(o);
Xif eof(dvi_file) then abort('the file ended prematurely!');
X@.the file ended prematurely@>
X@<Start translation of command |o| and |goto| the appropriate label to
X  finish the job@>;
Xfin_set: @<Finish a command that either sets or puts a character, then
X    |goto move_right| or |done|@>;
Xfin_rule: @<Finish a command that either sets or puts a rule, then
X    |goto move_right| or |done|@>;
Xmove_right: @<Finish a command that sets |h:=h+q|, then |goto done|@>;
Xshow_state: ;
Xdone: ;
Xend
X
X@ The multiway switch in |first_par|, above, was organized by the length
Xof each command; the one in |do_page| is organized by the semantics.
X
X@<Start translation...@>=
Xif o<set_char_0+128 then @<Translate a |set_char| command@>
Xelse case o of
X  four_cases(set1): begin out_char(p,hh,vv); goto fin_set;
X    end;
X  set_rule: begin goto fin_rule;
X    end;
X  put_rule: begin goto fin_rule;
X    end;
X  @t\4@>@<Cases for commands |nop|, |bop|, \dots, |pop|@>@;
X  @t\4@>@<Cases for horizontal motion@>@;
X  othercases if special_cases(o,p,a) then goto done@+else goto 9998
X  endcases
X
X@ @<Declare the function called |special_cases|@>=
Xfunction special_cases(@!o:eight_bits;@!p,@!a:integer):boolean;
Xlabel change_font,move_down,done,9998;
Xvar q:integer; {parameter of the current command}
X@!k:integer; {loop index}
X@!bad_char:boolean; {has a non-ascii character code appeared in this \\{xxx}?}
X@!pure:boolean; {is the command error-free?}
Xbegin pure:=true;
Xcase o of
Xfour_cases(put1): begin goto done;
X  end;
X@t\4@>@<Cases for vertical motion@>@;
X@t\4@>@<Cases for fonts@>@;
Xfour_cases(xxx1): @<Translate an |xxx| command and |goto done|@>;
Xpre: begin error('preamble command within a page!'); goto 9998;
X  end;
X@.preamble command within a page@>
Xpost,post_post: begin error('postamble command within a page!'); goto 9998;
X@.postamble command within a page@>
X  end;
Xothercases begin error('undefined command ',o:0,'!');
X  goto done;
X@.undefined command@>
X  end
Xendcases;
Xmove_down: @<Finish a command that sets |v:=v+p|, then |goto done|@>;
Xchange_font: @<Finish a command that changes the current font,
X  then |goto done|@>;
X9998: pure:=false;
Xdone: special_cases:=pure;
Xend;
X
X@ @<Cases for commands |nop|, |bop|, \dots, |pop|@>=
Xnop: begin goto done;
X  end;
Xbop: begin error('bop occurred before eop'); goto 9998;
X@.bop occurred before eop@>
X  end;
Xeop: begin 
X  if s<>0 then error('stack not empty at end of page (level ',
X    s:0,')!');
X@.stack not empty...@>
X  do_page:=true; flush_page; goto 9999;
X  end;
Xpush: begin 
X  if s=max_s_so_far then
X    begin max_s_so_far:=s+1;
X    if s=max_s then error('deeper than claimed in postamble!');
X@.deeper than claimed...@>
X@.push deeper than claimed...@>
X    if s=stack_size then
X      begin error('DVIDOC capacity exceeded (stack size=',
X        stack_size:0,')'); goto 9998;
X      end;
X    end;
X  hstack[s]:=h; vstack[s]:=v; wstack[s]:=w;
X  xstack[s]:=x; ystack[s]:=y; zstack[s]:=z;
X  hhstack[s]:=hh; vvstack[s]:=vv; incr(s); ss:=s-1; goto show_state;
X  end;
Xpop: begin 
X  if s=0 then error('Pop illegal at level zero!')
X  else  begin decr(s); hh:=hhstack[s]; vv:=vvstack[s];
X    h:=hstack[s]; v:=vstack[s]; w:=wstack[s];
X    x:=xstack[s]; y:=ystack[s]; z:=zstack[s];
X    end;
X  ss:=s; goto show_state;
X  end;
X
X@ Rounding to the nearest pixel is best done in the manner shown here, so as
Xto be inoffensive to the eye: When the horizontal motion is small, like a
Xkern, |hh| changes by rounding the kern; but when the motion is large, |hh|
Xchanges by rounding the true position |h| so that accumulated rounding errors
Xdisappear.
X
X
X@d out_space==if abs(p)>=font_space[cur_font] then
X    begin hh:=horiz_pixel_round(h+p);
X    end
X  else hh:=hh+horiz_pixel_round(p);
X  q:=p; goto move_right
X
X@<Cases for horizontal motion@>=
Xfour_cases(right1):begin out_space;
X  end;
Xw0,four_cases(w1):begin w:=p; out_space;
X  end;
Xx0,four_cases(x1):begin x:=p; out_space;
X  end;
X
X@ Vertical motion is done similarly, but with the threshold between
X``small'' and ``large'' increased by a factor of five. The idea is to make
Xfractions like ``$1\over2$'' round consistently, but to absorb accumulated
Xrounding errors in the baseline-skip moves.
X
X@d out_vmove==if abs(p)>=5*font_space[cur_font] then vv:=vert_pixel_round(v+p)
X  else vv:=vv+vert_pixel_round(p);
X  goto move_down
X
X@<Cases for vertical motion@>=
Xfour_cases(down1):begin out_vmove;
X  end;
Xy0,four_cases(y1):begin y:=p; out_vmove;
X  end;
Xz0,four_cases(z1):begin z:=p; out_vmove;
X  end;
X
X@ @<Cases for fonts@>=
Xsixty_four_cases(fnt_num_0): begin 
X  goto change_font;
X  end;
Xfour_cases(fnt1): begin 
X  goto change_font;
X  end;
Xfour_cases(fnt_def1): begin 
X  define_font(p); goto done;
X  end;
X
X@ @<Translate an |xxx| command and |goto done|@>=
Xbegin write(term_out,'xxx'''); bad_char:=false;
Xfor k:=1 to p do
X  begin 
X    q:=get_byte;
X    if 
X      (q>="!")and(q<="~") then write(term_out,xchr[q])
X      else bad_char:=true
X  end;
Xwrite(term_out,'''');
Xif bad_char then error('non-ascii character in xxx command!');
X@.non-ascii character...@>
Xgoto done;
Xend
X
X@ @<Translate a |set_char|...@>=
Xbegin 
X      out_char(p,hh,vv)  
Xend
X
X@ @<Finish a command that either sets or puts a character...@>=
Xif font_ec[cur_font]=256 then p:=256; {width computation for oriental fonts}
Xif (p<font_bc[cur_font])or(p>font_ec[cur_font]) then q:=invalid_width
Xelse q:=char_width(cur_font)(p);
Xif q=invalid_width then
X  begin error('character ',p:0,' invalid in font ');
X@.character $c$ invalid...@>
X  print_font(cur_font);
X  if cur_font<>nf then write(term_out,'!');
X  end;
Xif o>=put1 then goto done;
Xif q=invalid_width then q:=0
Xelse hh:=hh+char_pixel_width(cur_font)(p);
Xgoto move_right
X
X@ @<Finish a command that either sets or puts a rule...@>=
Xq:=signed_quad;
Xif (p>0) and (q>0) then
X  for i:=hh to hh+horiz_rule_pixels(q)-1 do
X    for j:=vv downto vv-vert_rule_pixels(p)+1 do
X      out_char(xord['-'],i,j);
Xif o=put_rule then goto done;
Xhh:=hh+horiz_rule_pixels(q); goto move_right
X
X@ Since \.{DVIDOC} is intended to diagnose strange errors, it checks
Xcarefully to make sure that |h| and |v| do not get out of range.
XNormal \.{DVI}-reading programs need not do this.
X
X@d infinity==@'17777777777 {$\infty$ (approximately)}
X
X@<Finish a command that sets |h:=h+q|, then |goto done|@>=
Xif (h>0)and(q>0) then if h>infinity-q then
X  begin error('arithmetic overflow! parameter changed from ',
X@.arithmetic overflow...@>
X    q:0,' to ',infinity-h:0);
X  q:=infinity-h;
X  end;
Xif (h<0)and(q<0) then if -h>q+infinity then
X  begin error('arithmetic overflow! parameter changed from ',
X    q:0, ' to ',(-h)-infinity:0);
X  q:=(-h)-infinity;
X  end;
Xh:=h+q;
Xif abs(h)>max_h_so_far then
X  begin max_h_so_far:=abs(h);
X  if abs(h)>max_h then error('warning: |h|>',max_h_so_far:0,'!');
X@.warning: |h|...@>
X  end;
Xgoto done
X
X@ @<Finish a command that sets |v:=v+p|, then |goto done|@>=
Xif (v>0)and(p>0) then if v>infinity-p then
X  begin error('arithmetic overflow! parameter changed from ',
X@.arithmetic overflow...@>
X    p:0,' to ',infinity-v:0);
X  p:=infinity-v;
X  end;
Xif (v<0)and(p<0) then if -v>p+infinity then
X  begin error('arithmetic overflow! parameter changed from ',
X    p:0, ' to ',(-v)-infinity:0);
X  p:=(-v)-infinity;
X  end;
Xv:=v+p;
Xif abs(v)>max_v_so_far then
X  begin max_v_so_far:=abs(v);
X  if abs(v)>max_v then error('warning: |v|>',max_v_so_far:0,'!');
X@.warning: |v|...@>
X  end;
Xgoto done
X
X@ @<Finish a command that changes the current font...@>=
Xfont_num[nf]:=p; cur_font:=0;
Xwhile font_num[cur_font]<>p do incr(cur_font);
Xgoto done
X
X@* Skipping pages.
X@ Global variables called |old_backpointer| and |new_backpointer|
Xare used to check whether the back pointers are properly set up.
XAnother one tells whether we have already found the starting page.
X
X@<Glob...@>=
X@!old_backpointer:integer; {the previous |bop| command location}
X@!new_backpointer:integer; {the current |bop| command location}
X@!started:boolean; {has the starting page been found?}
X
X@ @<Set init...@>=
Xold_backpointer:=-1; started:=false;
X
X@ @<Pass a |bop| command, setting up the |count| array@>=
Xnew_backpointer:=cur_loc-1; incr(page_count);
Xfor k:=0 to 9 do count[k]:=signed_quad;
Xif signed_quad<>old_backpointer
X  then write_ln(term_out,'backpointer in byte ',cur_loc-4:0,
X    ' should be ',old_backpointer:0,'!');
X@.backpointer...should be p@>
Xold_backpointer:=new_backpointer
X
X@* Using the backpointers.
XFirst comes a routine that illustrates how to find the postamble quickly.
X
X@<Find the postamble, working back from the end@>=
Xn:=dvi_length;
Xif n<57 then bad_dvi('only ',n:0,' bytes long');
X@.only n bytes long@>
Xm:=n-4;
Xrepeat if m=0 then bad_dvi('all 223s');
X@.all 223s@>
Xmove_to_byte(m); k:=get_byte; decr(m);
Xuntil k<>223;
Xif k<>id_byte then bad_dvi('ID byte is ',k:0);
X@.ID byte is wrong@>
Xmove_to_byte(m-3); q:=signed_quad;
Xif (q<0)or(q>m-36) then bad_dvi('post pointer ',q:0,' at byte ',m-3:0);
X@.post pointer is wrong@>
Xmove_to_byte(q); k:=get_byte;
Xif k<>post then bad_dvi('byte ',q:0,' is not post');
X@.byte n is not post@>
Xpost_loc:=q; first_backpointer:=signed_quad
X
X@ Note that the last steps of the above code save the locations of the
Xthe |post| byte and the final |bop|.  We had better declare these global
Xvariables, together with another one that we will need shortly.
X
X@<Glob...@>=
X@!post_loc:integer; {byte location where the postamble begins}
X@!first_backpointer:integer; {the pointer following |post|}
X@!start_loc:integer; {byte location of the first page to process}
X
X@ The next little routine shows how the backpointers can be followed
Xto move through a \.{DVI} file in reverse order. Ordinarily a \.{DVI}-reading
Xprogram would do this only if it wants to print the pages backwards or
Xif it wants to find a specified starting page that is not necessarily the
Xfirst page in the file; otherwise it would of course be simpler and faster
Xjust to read the whole file from the beginning.
X
X@<Count the pages and move to the starting page@>=
Xq:=post_loc; p:=first_backpointer; start_loc:=-1;
Xif p>=0 then
X  repeat {now |q| points to a |post| or |bop| command; |p>=0| is prev pointer}
X  if p>q-46 then
X    bad_dvi('page link ',p:0,' after byte ',q:0);
X@.page link wrong...@>
X  q:=p; move_to_byte(q); k:=get_byte;
X  if k=bop then incr(page_count)
X  else bad_dvi('byte ',q:0,' is not bop');
X@.byte n is not bop@>
X  for k:=0 to 9 do count[k]:=signed_quad;
X  if start_match then start_loc:=q;
X  p:=signed_quad;
X  until p<0;
Xif start_loc<0 then abort('starting page number could not be found!');
Xmove_to_byte(start_loc+1); old_backpointer:=start_loc;
Xfor k:=0 to 9 do count[k]:=signed_quad;
Xp:=signed_quad; started:=true
X
X@* Reading the postamble.
XNow imagine that we are reading the \.{DVI} file and positioned just
Xfour bytes after the |post| command. That, in fact, is the situation,
Xwhen the following part of \.{DVIDOC} is called upon to read, translate,
Xand check the rest of the postamble.
X
X@p procedure read_postamble;
Xvar k:integer; {loop index}
X@!p,@!q,@!m:integer; {general purpose registers}
Xbegin 
Xmove_to_byte(cur_loc+12); {skip over numerator, denominator, and magnification}
Xmax_v:=signed_quad; max_h:=signed_quad;@/
Xmax_s:=get_two_bytes; total_pages:=get_two_bytes;@/
X@<Process the font definitions of the postamble@>;
X@<Make sure that the end of the file is well-formed@>;
Xend;
X
X@ When we get to the present code, the |post_post| command has
Xjust been read.
X
X@<Make sure that the end of the file is well-formed@>=
Xq:=signed_quad;
Xm:=get_byte;
Xk:=cur_loc; m:=223;
Xwhile (m=223)and not eof(dvi_file) do m:=get_byte;
Xif not eof(dvi_file) then abort('signature in byte ',cur_loc-1:0,
X@.signature...should be...@>
X    ' should be 223!')
Xelse if cur_loc<k+4 then
X  write_ln(term_out,'not enough signature bytes at end of file (',
X@.not enough signature bytes...@>
X    cur_loc-k:0,')');
X
X@ @<Process the font definitions...@>=
Xrepeat k:=get_byte;
Xif (k>=fnt_def1)and(k<fnt_def1+4) then
X  begin p:=first_par(k); define_font(p); write_ln(term_out,' '); k:=nop;
X  end;
Xuntil k<>nop
X
X@* The main program.
XNow we are ready to put it all together. This is where \.{DVIDOC} starts,
Xand where it ends.
X
X@p begin 
Xif (argc <> 3) then
X    begin
X    error('Usage: dvidoc <dvi-file> <doc-file>');
X    goto done;
X    end;
Xinitialize; {get all variables initialized}
Xdialog; {set up all the options}
X@<Process the preamble@>;
X@<Find the postamble, working back from the end@>;
Xin_postamble:=true; read_postamble; in_postamble:=false;
X@<Count the pages and move to the starting page@>;
Xif not in_postamble then @<Translate up to |max_pages| pages@>;
Xfinal_end:end.
X
X@ The main program needs a few global variables in order to do its work.
X
X@<Glob...@>=
X@!k,@!m,@!n,@!p,@!q:integer; {general purpose registers}
X
X@ A \.{DVI}-reading program that reads the postamble first need not look at the
Xpreamble; but \.{DVIDOC} looks at the preamble in order to do error
Xchecking, and to display the introductory comment.
X
X@<Process the preamble@>=
Xopen_dvi_file;
Xp:=get_byte; {fetch the first byte}
Xif p<>pre then bad_dvi('First byte isn''t start of preamble!');
X@.First byte isn't...@>
Xp:=get_byte; {fetch the identification byte}
X@<Compute the conversion factor@>;
Xp:=get_byte; {fetch the length of the introductory comment}
Xwrite(term_out,'''');
Xwhile p>0 do
X  begin decr(p); write(term_out,xchr[get_byte]);
X  end;
Xwrite_ln(term_out,'''')
X
X@ The conversion factors |horiz_conv| and 
X|vert_conv| are figured as follows: There are exactly
X|n/d| \.{DVI} units per decimicron, and 254000 decimicrons per inch,
Xand |horiz_resolution| or |vert_resolution| characters per inch. Then we have to adjust this
Xby the stated amount of magnification.
X
X@<Compute the conversion factor@>=
Xnumerator:=signed_quad; denominator:=signed_quad;
Xif numerator<=0 then bad_dvi('numerator is ',numerator:0);
X@.numerator is wrong@>
Xif denominator<=0 then bad_dvi('denominator is ',denominator:0);
X@.denominator is wrong@>
Xhoriz_conv:=(numerator/254000.0)*(horiz_resolution/denominator);
Xvert_conv:=(numerator/254000.0)*(vert_resolution/denominator);
Xmag:=signed_quad;
Xif new_mag>0 then mag:=new_mag
Xelse if mag<=0 then bad_dvi('magnification is ',mag:0);
X@.magnification is wrong@>
Xtrue_horiz_conv:=horiz_conv; horiz_conv:=true_horiz_conv*(mag/1000.0);
Xtrue_vert_conv:=vert_conv; vert_conv:=true_vert_conv*(mag/1000.0);
X
X@ The code shown here uses a convention that has proved to be useful:
XIf the starting page was specified as, e.g., `\.{1.*.-5}', then
Xall page numbers in the file are displayed by showing the values of
Xcounts 0, 1, and@@2, separated by dots. Such numbers can, for example,
Xbe displayed on the console of a printer when it is working on that
Xpage.
X
X@<Translate up to...@>=
Xbegin while max_pages>0 do
X  begin decr(max_pages);
X  write_ln(term_out); write(term_out,'Beginning of page ');
X  for k:=0 to start_vals do
X    begin write(term_out,count[k]:0);
X    if k<start_vals then write(term_out,'.')
X    else write_ln(term_out);
X    end;
X  if not do_page then abort('page ended unexpectedly!');
X@.page ended unexpectedly@>
X  repeat k:=get_byte;
X  if (k>=fnt_def1)and(k<fnt_def1+4) then
X    begin p:=first_par(k); define_font(p); k:=nop;
X    end;
X  until k<>nop;
X  if k=post then
X    begin in_postamble:=true; goto done;
X    end;
X  if k<>bop then bad_dvi('byte ',cur_loc-1:0,' is not bop');
X@.byte n is not bop@>
X  @<Pass a |bop|...@>;
X  end;
Xdone:end
X
X@* System-dependent changes.
XThis module should be replaced, if necessary, by changes to the program
Xthat are necessary to make \.{DVIDOC} work at a particular installation.
XIt is usually best to design your change file so that all changes to
Xprevious modules preserve the module numbering; then everybody's version
Xwill be consistent with the printed program. More extensive changes,
Xwhich introduce new modules, can be inserted here; then only the index
Xitself will get a new module number.
X
X@* Index.
XPointers to error messages appear here together with the section numbers
Xwhere each ident\-i\-fier is used.
!FaR!OuT!
if [ ! -d dvidoc ]
then
	mkdir dvidoc
	echo mkdir dvidoc
fi
echo x - dvidoc/dvityext.c
sed -e 's/^X//' > dvidoc/dvityext.c << '!FaR!OuT!'
X/* External procedures for dvitype				*/
X/*   Written by: H. Trickey, 2/19/83 (adapted from TeX's ext.c) */
X
X#include "texpaths.h"		/* defines default TEXFONTS path */
X#include "h00vars.h"		/* defines Pascal I/O structure */
X
Xchar *fontpath;
X
Xchar *getenv();
X
X/*
X * setpaths is called to set up the pointer fontpath
X * as follows:  if the user's environment has a value for TEXFONTS
X * then use it;  otherwise, use defaultfontpath.
X */
Xsetpaths()
X{
X	register char *envpath;
X	
X	if ((envpath = getenv("TEXFONTS")) != NULL)
X	    fontpath = envpath;
X	else
X	    fontpath = defaultfontpath;
X}
X
X#define namelength 100   /* should agree with dvitype.ch */
Xextern char curname[],realnameoffile[]; /* these have size namelength */
X
X/*
X *	testaccess(amode,filepath)
X *
X *  Test whether or not the file whose name is in the global curname
X *  can be opened for reading (if mode=READACCESS)
X *  or writing (if mode=WRITEACCESS).
X *
X *  The filepath argument is one of the ...FILEPATH constants defined below.
X *  If the filename given in curname does not begin with '/', we try 
X *  prepending all the ':'-separated areanames in the appropriate path to the
X *  filename until access can be made, if it ever can.
X *
X *  The realnameoffile global array will contain the name that yielded an
X *  access success.
X */
X
X#define READACCESS 4
X#define WRITEACCESS 2
X
X#define NOFILEPATH 0
X#define FONTFILEPATH 3
X
Xbool
Xtestaccess(amode,filepath)
X    int amode,filepath;
X{
X    register bool ok;
X    register char *p;
X    char *curpathplace;
X    int f;
X    
X    switch(filepath) {
X	case NOFILEPATH: curpathplace = NULL; break;
X	case FONTFILEPATH: curpathplace = fontpath; break;
X	}
X    if (curname[0]=='/')	/* file name has absolute path */
X	curpathplace = NULL;
X    do {
X	packrealnameoffile(&curpathplace);
X	if (amode==READACCESS)
X	    /* use system call "access" to see if we could read it */
X	    if (access(realnameoffile,READACCESS)==0) ok = TRUE;
X	    else ok = FALSE;
X	else {
X	    /* WRITEACCESS: use creat to see if we could create it, but close
X	    the file again if we're OK, to let pc open it for real */
X	    f = creat(realnameoffile,0666);
X	    if (f>=0) ok = TRUE;
X	    else ok = FALSE;
X	    if (ok)
X		close(f);
X	    }
X    } while (!ok && curpathplace != NULL);
X    if (ok) {  /* pad realnameoffile with blanks, as Pascal wants */
X	for (p = realnameoffile; *p != '\0'; p++)
X	    /* nothing: find end of string */ ;
X	while (p < &(realnameoffile[namelength]))
X	    *p++ = ' ';
X	}
X    return (ok);
X}
X
X/*
X * packrealnameoffile(cpp) makes realnameoffile contain the directory at *cpp,
X * followed by '/', followed by the characters in curname up until the
X * first blank there, and finally a '\0'.  The cpp pointer is left pointing
X * at the next directory in the path.
X * But: if *cpp == NULL, then we are supposed to use curname as is.
X */
Xpackrealnameoffile(cpp)
X    char **cpp;
X{
X    register char *p,*realname;
X    
X    realname = realnameoffile;
X    if ((p = *cpp)!=NULL) {
X	while ((*p != ':') && (*p != '\0')) {
X	    *realname++ = *p++;
X	    if (realname == &(realnameoffile[namelength-1]))
X		break;
X	    }
X	if (*p == '\0') *cpp = NULL; /* at end of path now */
X	else *cpp = p+1; /* else get past ':' */
X	*realname++ = '/';  /* separate the area from the name to follow */
X	}
X    /* now append curname to realname... */
X    p = curname;
X    while (*p != ' ') {
X	if (realname >= &(realnameoffile[namelength-1])) {
X	    fprintf(stderr,"! Full file name is too long\n");
X	    break;
X	    }
X	*realname++ = *p++;
X	}
X    *realname = '\0';
X}
!FaR!OuT!
if [ ! -d dvidoc ]
then
	mkdir dvidoc
	echo mkdir dvidoc
fi
echo x - dvidoc/dvityext.h
sed -e 's/^X//' > dvidoc/dvityext.h << '!FaR!OuT!'
Xprocedure setpaths;
X    external;
X
Xfunction testaccess(accessmode:integer; filepath:integer): boolean;
X    external;
!FaR!OuT!
if [ ! -d dvidoc ]
then
	mkdir dvidoc
	echo mkdir dvidoc
fi
echo x - dvidoc/h00vars.h
sed -e 's/^X//' > dvidoc/h00vars.h << '!FaR!OuT!'
X/* Copyright (c) 1979 Regents of the University of California */
X
X/* sccsid[] = "@(#)h00vars.h 1.10 1/10/83"; */
X
X#include <stdio.h>
X#include "whoami.h"
X
X#define PXPFILE		"pmon.out"
X#define	BITSPERBYTE	8
X#define	BITSPERLONG	(BITSPERBYTE * sizeof(long))
X#define LG2BITSBYTE	03
X#define MSKBITSBYTE	07
X#define LG2BITSLONG	05
X#define MSKBITSLONG	037
X#define HZ		60
X#define	MAXLVL		20
X#define MAXERRS		75
X#define NAMSIZ		76
X#define MAXFILES	32
X#define PREDEF		2
X#define STDLVL	((struct iorec *)(0xc00cc001))
X#define GLVL	((struct iorec *)(0xc00cc000))
X#define FILNIL		((struct iorec *)(0))
X#define INPUT		((struct iorec *)(&input))
X#define OUTPUT		((struct iorec *)(&output))
X#define ERR		((struct iorec *)(&_err))
Xtypedef enum {FALSE, TRUE} bool;
X
X/*
X * runtime display structure
X */
Xstruct display {
X	char	*ap;
X	char	*fp;
X};
X
X/*
X * formal routine structure
X */
Xstruct formalrtn {
X	long		(*fentryaddr)();	/* formal entry point */
X	long		fbn;			/* block number of function */
X	struct display	fdisp[ MAXLVL ];	/* saved at first passing */
X};
X
X/*
X * program variables
X */
Xextern struct display	_disply[MAXLVL];/* runtime display */
Xextern int		_argc;		/* number of passed args */
Xextern char		**_argv;	/* values of passed args */
Xextern long		_stlim;		/* statement limit */
Xextern long		_stcnt;		/* statement count */
Xextern long		_seed;		/* random number seed */
Xextern char		*_maxptr;	/* maximum valid pointer */
Xextern char		*_minptr;	/* minimum valid pointer */
Xextern long		_pcpcount[];	/* pxp buffer */
X
X/*
X * file structures
X */
Xstruct iorechd {
X	char		*fileptr;	/* ptr to file window */
X	long		lcount;		/* number of lines printed */
X	long		llimit;		/* maximum number of text lines */
X	FILE		*fbuf;		/* FILE ptr */
X	struct iorec	*fchain;	/* chain to next file */
X	struct iorec	*flev;		/* ptr to associated file variable */
X	char		*pfname;	/* ptr to name of file */
X	short		funit;		/* file status flags */
X	unsigned short	fblk;		/* index into active file table */
X	long		fsize;		/* size of elements in the file */
X	char		fname[NAMSIZ];	/* name of associated UNIX file */
X};
X
Xstruct iorec {
X	char		*fileptr;	/* ptr to file window */
X	long		lcount;		/* number of lines printed */
X	long		llimit;		/* maximum number of text lines */
X	FILE		*fbuf;		/* FILE ptr */
X	struct iorec	*fchain;	/* chain to next file */
X	struct iorec	*flev;		/* ptr to associated file variable */
X	char		*pfname;	/* ptr to name of file */
X	short		funit;		/* file status flags */
X	unsigned short	fblk;		/* index into active file table */
X	long		fsize;		/* size of elements in the file */
X	char		fname[NAMSIZ];	/* name of associated UNIX file */
X	char		buf[BUFSIZ];	/* I/O buffer */
X	char		window[1];	/* file window element */
X};
X
X/*
X * unit flags
X */
X#define SPEOLN	0x100	/* 1 => pseudo EOLN char read at EOF */
X#define	FDEF	0x080	/* 1 => reserved file name */
X#define	FTEXT	0x040	/* 1 => text file, process EOLN */
X#define	FWRITE	0x020	/* 1 => open for writing */
X#define	FREAD	0x010	/* 1 => open for reading */
X#define	TEMP	0x008	/* 1 => temporary file */
X#define	SYNC	0x004	/* 1 => window is out of sync */
X#define	EOLN	0x002	/* 1 => at end of line */
X#define	EOFF	0x001	/* 1 => at end of file */
X
X/*
X * file routines
X */
Xextern struct iorec	*GETNAME();
Xextern char		*MKTEMP();
Xextern char		*PALLOC();
X
X/*
X * file record variables
X */
Xextern struct iorechd	_fchain;	/* head of active file chain */
Xextern struct iorec	*_actfile[];	/* table of active files */
Xextern long		_filefre;	/* last used entry in _actfile */
X
X/*
X * standard files
X */
Xextern struct iorechd	input;
Xextern struct iorechd	output;
Xextern struct iorechd	_err;
X
X/*
X * seek pointer struct for TELL, SEEK extensions
X */
Xstruct seekptr {
X	long	cnt;
X};
!FaR!OuT!
if [ ! -d dvidoc ]
then
	mkdir dvidoc
	echo mkdir dvidoc
fi
echo x - dvidoc/texpaths.h
sed -e 's/^X//' > dvidoc/texpaths.h << '!FaR!OuT!'
X/*
X * This file defines the default paths that will be used for TeX software.
X * (These paths are used if the user's environment doesn't specify paths.)
X *
X * Paths should be colon-separated and no longer than MAXINPATHCHARS-1
X * (for defaultinputpath) or MAXOTHPATHCHARS (for other default paths).
X */
X
X#define MAXINPATHCHARS  700	/* maximum number of chars in an input path */
X
X#define defaultinputpath  ".:/usr/new/lib/tex/macros"
X    /* this should always start with "." */
X
X#define MAXOTHPATHCHARS 100     /* other paths should be much shorter */
X
X#define defaultfontpath   "/usr/local/lib/tex/fonts"
X    /* it is probably best not to include "." here to prevent confusion
X       by spooled device drivers that think they know where the fonts
X       really are */
X#define defaultformatpath ".:/usr/new/lib/tex/macros"
X#define defaultpoolpath   ".:/usr/new/lib/tex"
X
!FaR!OuT!
if [ ! -d dvidoc ]
then
	mkdir dvidoc
	echo mkdir dvidoc
fi
echo x - dvidoc/whoami.h
sed -e 's/^X//' > dvidoc/whoami.h << '!FaR!OuT!'
!FaR!OuT!
exit
-- 
		Scott Simpson
		TRW Electronics and Defense Sector
		...{decvax,ihnp4,ucbvax}!trwrb!simpson