summaryrefslogtreecommitdiff
path: root/dviware/psprint/vms/dvireader.mod
blob: 0ff1ac3fa881aea4046e25d81eaf29907d2216a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
IMPLEMENTATION MODULE DVIReader;

(* Author:         Andrew Trevorrow
   Implementation: University of Hamburg Modula-2 under VAX/VMS version 4
   Date Started:   August, 1984

   Description:
   Implements routines and data structures for use in a TeX82 DVI translator.
   Much of the code in DVIReader is based on DVITYPE 2.7 by Donald Knuth.
   DVITYPE is a program for verifying a DVI file and also serves as a model
   for other DVI-reading programs.  See the "TeXWARE" manual by Knuth for a
   complete description of DVITYPE and the format of DVI files.
   For efficiency reasons we assume the given DVI file is formatted correctly;
   it is the job of DVITYPE to diagnose bad DVI files.

   Revised:
   August, 1986
 - PSDVI requires that MoveToDVIPage no longer assumes InterpretPage has
   been called after any previous MoveTo... routine.

   December, 1986
 - Initialize fontexists flag to FALSE when reading postamble.

   June--August, 1988 (while at Aston University)
 - Import hoffset and voffset from Options to handle shifting of page.
*)

FROM SYSTEM IMPORT
   ADDRESS,                (* byte address *)
   ADR, BYTE;

FROM Storage IMPORT
   ALLOCATE, DEALLOCATE;   (* need for NEW and DISPOSE *)

FROM VMS IMPORT
   SYS$OPEN, SYS$CRMPSC, SYS$DASSGN, SYS$DELTVA;

FROM SSDefinitions IMPORT
   SS$_ENDOFFILE;

FROM SECDefinitions IMPORT
   SEC$V_EXPREG;

FROM RMS IMPORT
   FAB, InitFab,
   FOPset, FOPtype,
   FACset, FACtype,
   SHRset, SHRtype;

(* DEBUG
(* DVIReader will only do terminal output while debugging. *)
FROM TermOut IMPORT
   Write, WriteString, WriteLn, WriteInt, WriteCard, Halt;
GUBED *)

FROM Options IMPORT
   hoffset, voffset;


(*******************************************************************************
   DECLARATIONS FOR RANDOMLY ACCESSING A DVI FILE

   A DVI file is considered to be an array of 8-bit bytes, ending with at
   least 4 223 bytes and having a total length divisible by 4.
   Under VAX/VMS a DVI file has fixed-length, 512-byte records (1 per block).
   The last record/s will be padded with 223 bytes to ensure that the
   above conditions hold.  We will be randomly positioning to DVI bytes
   by setting DVIoffset, and reading bytes via GetDVIByte, SignedDVIByte etc.
*)

TYPE
   (* DVI file should never have more than MAX(INTEGER) bytes! *)
   DVIfile    = ARRAY [0..MAX(INTEGER)] OF BYTE;
   DVIpointer = POINTER TO DVIfile;                       (* never allocated! *)

VAR
   vas : ARRAY [0..1] OF ADDRESS;      (* start and end virtual addresses     *)
   DVIstart : DVIpointer;
   DVIoffset : CARDINAL;               (* current byte offset in DVIfile      *)
   channel : CARDINAL;                 (* fab.STV returned by SYS$OPEN        *)
   gsdnam : ARRAY [0..42] OF CHAR;     (* unused argument in SYS$CRPMSC       *)
   status : CARDINAL;
   fab : FAB;
   postpostid : CARDINAL;              (* offset of postpost's id byte        *)

(******************************************************************************)

PROCEDURE OpenDVIFile (name : ARRAY OF CHAR);

(* If the given file can be opened and is a valid TeX82 DVI file then we
   process the postamble and initialize currDVIpage and currTeXpage.
*)

VAR i : CARDINAL;

BEGIN
InitFab(fab);                        (* initialize fab *)
WITH fab DO
   FNA := ADR(name);                 (* DVI file name *)
   FNS := BYTE(LEN(name));           (* bytes in file name *)
   FAC := FACset{FAC$BRO,FAC$GET};   (* read-only *)
   SHR := SHRset{SHR$GET};           (* share file with other readers *)
   FOP := FOPset{FOP$UFO};           (* need for SYS$CRMPSC *)
   RTV := BYTE(-1);                  (* for more efficient mapping *)
END;
status := SYS$OPEN(ADR(fab),0,0);    (* open the file *)
IF ODD(status) THEN
   WITH fab DO
      channel := STV;                (* channel on which file is open *)
   END;
   (* now map entire DVI file into virtual address space *)
   vas[0] := 0;
   vas[1] := 0;
   status := SYS$CRMPSC
                 (ADR(vas),          (* starting and ending addresses *)
                  ADR(vas),          (* addresses returned *)
                  0,
                  {SEC$V_EXPREG},    (* pages mapped into 1st available space *)
                  gsdnam,0,0,
                  channel,           (* channel on which file has been opened *)
                  0,0,0,
                  36                 (* large page fault cluster size *)
                 );
   IF status = SS$_ENDOFFILE THEN
      DVIErrorRoutine(DVIempty);     (* given file is empty *)
   ELSIF NOT ODD(status) THEN
      (* DEBUG
         WriteString('SYS$CRMPSC failed! status='); WriteCard(status);
         WriteLn; Halt(2);
      GUBED *)
      DVIErrorRoutine(DVIcatastrophe);
   ELSE
      (* Now that the entire DVI file is mapped into virtual memory we can
         access any DVI byte as an offset from the address in vas[0].
      *)
      DVIstart := vas[0];
      (* move to last DVI byte *)
      DVIoffset := CARDINAL(ADDRESS(vas[1]) - ADDRESS(DVIstart));
      (* check for trailing NULs first in case DVI file has come
         from non-VMS environment
      *)
      WHILE (DVIoffset > 0) AND (CARDINAL(DVIstart^[DVIoffset]) = 0) DO
         DEC(DVIoffset);             (* skip NUL byte *)
      END;
      WHILE (DVIoffset > 0) AND (CARDINAL(DVIstart^[DVIoffset]) = 223) DO
         DEC(DVIoffset);             (* skip 223 byte *)
      END;
      postpostid := DVIoffset;       (* remember position of id byte *)
      IF GetDVIByte() <> 2 THEN
         (* DEBUG
            WriteString('Bad DVI file! id byte is not 2.'); WriteLn;
            Halt(2);
         GUBED *)
         DVIErrorRoutine(DVIbadid);  (* not a valid TeX82 DVI file *)
      ELSE
         ProcessPostamble;           (* get DVImag, totalpages, etc *)
         ProcessFontDefs;            (* build and initialize font list *)
         currDVIpage := 0;           (* we haven't processed a page yet *)
         FOR i := 0 TO 9 DO
            currTeXpage[i] := 0;
         END;
      END;
   END;
ELSE
   DVIErrorRoutine(DVIunopened);     (* given file could not be opened *)
END;
END OpenDVIFile;

(******************************************************************************)

(* Here are the functions used to get byte/s from DVIfile.
   They are essentially the same as those used in DVITYPE.
*)

PROCEDURE GetDVIByte () : INTEGER;

(* Returns the value (unsigned) of the byte at DVIoffset and
   advances DVIoffset for the next GetDVIByte.
*)

VAR b : CARDINAL;

BEGIN
b := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
RETURN b;
END GetDVIByte;

(******************************************************************************)

PROCEDURE SignedDVIByte () : INTEGER;      (* the next byte, signed *)

VAR b : CARDINAL;

BEGIN
b := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
IF b < 128 THEN
   RETURN b;
ELSE
   RETURN b - 256;
END;
END SignedDVIByte;

(******************************************************************************)

PROCEDURE GetTwoDVIBytes () : INTEGER;     (* the next 2 bytes, unsigned *)

VAR a, b : CARDINAL;

BEGIN
a := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
b := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
RETURN a * 256 + b;
END GetTwoDVIBytes;

(******************************************************************************)

PROCEDURE SignedDVIPair () : INTEGER;      (* the next 2 bytes, signed *)

VAR a, b : CARDINAL;

BEGIN
a := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
b := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
IF a < 128 THEN
   RETURN a * 256 + b;
ELSE
   RETURN (a - 256) * 256 + b;
END;
END SignedDVIPair;

(******************************************************************************)

PROCEDURE GetThreeDVIBytes () : INTEGER;   (* the next 3 bytes, unsigned *)

VAR a, b, c : CARDINAL;

BEGIN
a := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
b := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
c := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
RETURN (a * 256 + b) * 256 + c;
END GetThreeDVIBytes;

(******************************************************************************)

PROCEDURE SignedDVITrio () : INTEGER;      (* the next 3 bytes, signed *)

VAR a, b, c : CARDINAL;

BEGIN
a := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
b := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
c := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
IF a < 128 THEN
   RETURN (a * 256 + b) * 256 + c;
ELSE
   RETURN ((a - 256) * 256 + b) * 256 + c;
END;
END SignedDVITrio;

(******************************************************************************)

PROCEDURE SignedDVIQuad () : INTEGER;      (* the next 4 bytes, signed *)

VAR a, b, c, d : CARDINAL;

BEGIN
a := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
b := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
c := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
d := CARDINAL(DVIstart^[DVIoffset]);   INC(DVIoffset);
IF a < 128 THEN
   RETURN ((a * 256 + b) * 256 + c) * 256 + d;
ELSE
   RETURN (((a - 256) * 256 + b) * 256 + c) * 256 + d;
END;
END SignedDVIQuad;

(******************************************************************************)

PROCEDURE ProcessPostamble;

(* Having successfully opened the DVI file, we find the postamble
   and initialize these global variables:
   lastbop, num, den, DVImag, maxstack, totalpages.
   The font definitions are read by ProcessFontDefs.
*)

VAR postamblepos, postamble, pagehtplusdp, pagewidth : CARDINAL;

BEGIN
DVIoffset    := postpostid - 4;
postamblepos := SignedDVIQuad();   (* get post_post's postamble ptr *)
DVIoffset    := postamblepos;
postamble    := GetDVIByte();
lastbop      := SignedDVIQuad();
num          := SignedDVIQuad();
den          := SignedDVIQuad();
DVImag       := SignedDVIQuad();
pagehtplusdp := SignedDVIQuad();
pagewidth    := SignedDVIQuad();
maxstack     := SignedDVIPair();
totalpages   := SignedDVIPair();
IF maxstack > maxstacksize THEN
   (* DEBUG
      WriteString('Stack capacity exceeded!   maxstack = ');
      WriteCard(maxstack);
      WriteString(' but maxstacksize only = '); WriteCard(maxstacksize);
      WriteLn;
      Halt(2);
   GUBED *)
   DVIErrorRoutine(DVIstackoverflow);
   (* now we don't need to test for stack overflow in DoPush *)
END;
(* DEBUG
   WriteString('postamble opcode     ='); WriteInt(postamble);    WriteLn;
   WriteString('postion of last bop  ='); WriteInt(lastbop);      WriteLn;
   WriteString('num                  ='); WriteInt(num);          WriteLn;
   WriteString('den                  ='); WriteInt(den);          WriteLn;
   WriteString('DVI mag              ='); WriteInt(DVImag);       WriteLn;
   WriteString('ht+dp of tallest page='); WriteInt(pagehtplusdp); WriteLn;
   WriteString('width of widest page ='); WriteInt(pagewidth);    WriteLn;
   WriteString('max stack depth      ='); WriteInt(maxstack);     WriteLn;
   WriteString('total # of pages     ='); WriteInt(totalpages);   WriteLn;
GUBED *)
END ProcessPostamble;

(******************************************************************************)

PROCEDURE ProcessFontDefs;

(* Read the fntdef commands in the postamble (fntdef commands in the DVI
   pages will be skipped) and store the information in the font list.
   (Note that complete fontspecs are NOT built here because DVIReader does not
   want to know about the format or naming conventions of font files;
   the client module must handle all this in its PixelTableRoutine.)
   Since ProcessPostamble ended by reading the totalpages parameter, the
   next GetDVIByte should return nop or first fntdef.
*)

VAR f, c, s, d, a, l : INTEGER;      (* hold fntdef parameters *)
    i : INTEGER;   ch : CHAR;        (* for getting farea and fname *)
    farea, fname : fontstring;       (* a and l bytes long respectively *)

BEGIN
totalfonts := 0;     (* number of nodes in font list *)
fontlist   := NIL;
REPEAT
   DVIcommand := GetDVIByte();
   IF (DVIcommand >= fntdef1) AND (DVIcommand <= fntdef1+3) THEN
      CASE DVIcommand - fntdef1 OF
         0 : f := GetDVIByte() |
         1 : f := GetTwoDVIBytes() |
         2 : f := GetThreeDVIBytes() |
         3 : f := SignedDVIQuad()
      END;
      c := SignedDVIQuad();   (* checksum; ignore it *)
      s := SignedDVIQuad();   (* scaled size *)
      d := SignedDVIQuad();   (* design size *)
      a := GetDVIByte();      (* length of font area *)
      l := GetDVIByte();      (* length of font name *)
      farea := '';
      FOR i := 0 TO a-1 DO    (* read and store font area *)
         ch := CHR(GetDVIByte());
         IF i < maxfontspec THEN farea[i] := ch END;
      END;
      fname := '';
      FOR i := 0 TO l-1 DO    (* read and store font name *)
         ch := CHR(GetDVIByte());
         IF i < maxfontspec THEN fname[i] := ch END;
      END;
      NEW(currfont);
      WITH currfont^ DO
         fontused    := FALSE;
         fontnum     := f;
         scaledsize  := s;
         designsize  := d;
         fontarea    := farea; fontarealen := CARDINAL(a);
         fontname    := fname; fontnamelen := CARDINAL(l);
         fontspec    := '';
         fontspeclen := 0;        (* fontspec has to be built by client *)
         fontexists  := FALSE;    (* becomes TRUE if fontspec can be opened *)
         totalchars  := 0;
         charlist    := NIL;      (* first node allocated in DoFont *)
         chartail    := NIL;      (* nodes are added to tail of char list *)
         pixelptr    := NIL;      (* allocated once per font; see DoFont *)
         nextfont    := fontlist;
      END;
      fontlist := currfont;       (* add new font to head of list *)
      INC(totalfonts);
   ELSIF DVIcommand = nop THEN
      (* nop commands can occur between DVI commands *)
   ELSIF DVIcommand = postpost THEN
      (* we have reached end of postamble *)
   ELSE
      (* DEBUG
         WriteString('Unexpected DVI command in postamble = ');
         WriteCard(DVIcommand); WriteLn;
         Halt(2);
      GUBED *)
      DVIErrorRoutine(DVIcatastrophe);
   END;
UNTIL DVIcommand = postpost;
END ProcessFontDefs;


(*******************************************************************************
   DECLARATIONS FOR GETTING TO A DVI PAGE

   The user can select a particular page by specifying a DVI page
   number (from 1 to totalpages), or a TeX page number (based on the
   values of \count0,\count1,...,\count9), or simply requesting the next page
   in the DVI file (which depends on whether we are ascending or not).
   We will often need to follow the DVI backpointers to locate the bop byte
   of a selected page.
*)

VAR
   curreop,                     (* position of eop byte of current page       *)
   currbop,                     (* position of bop byte of current page       *)
   lastbop : CARDINAL;          (* position of last bop byte                  *)
   prevbop : INTEGER;           (* position of bop byte of previous page;
                                   note that prevbop of first page = -1       *)

(******************************************************************************)

PROCEDURE MoveToNextPage (ascending : BOOLEAN);

(* Move to next DVI page; whether we can will depend on the current DVI page
   and if we are ascending or descending.
*)

BEGIN
IF (currDVIpage = 1) AND (NOT ascending) THEN         (* do nothing *)
   RETURN;
ELSIF (currDVIpage = totalpages) AND ascending THEN   (* do nothing *)
   RETURN;
ELSIF currDVIpage = 0 THEN   (* we haven't processed a page yet *)
   IF ascending THEN         (* get first page *)
      ReadFirstBop;
   ELSE                      (* get last page *)
      currbop := lastbop;
      DVIoffset := currbop + 1;
      currDVIpage := totalpages;
   END;
ELSE
   IF ascending THEN
      (* currently positioned after eop of currDVIpage, so get next bop *)
      ReadNextBop;
   ELSE
      (* move to bop pointed to by currbop's backpointer *)
      currbop := prevbop;
      DVIoffset := currbop + 1;   (* move to byte after previous bop *)
      DEC(currDVIpage);
   END;
END;
ReadBopParameters;   (* update currTeXpage and prevbop *)
END MoveToNextPage;

(******************************************************************************)

PROCEDURE ReadFirstBop;

(* Read first bop by skipping past preamble; update currbop and currDVIpage. *)

VAR k, i, dummy : CARDINAL;

BEGIN
DVIoffset := 14;            (* position of preamble's k parameter *)
k := GetDVIByte();          (* length of x parameter *)
FOR i := 1 TO k DO
   dummy := GetDVIByte();   (* skip preamble comment *)
END;
REPEAT   (* skip any nops and fntdefs *)
   DVIcommand := GetDVIByte();
   IF (DVIcommand = nop) OR (DVIcommand = bop) THEN
      (* do nothing *)
   ELSIF (DVIcommand >= fntdef1) AND (DVIcommand <= fntdef1+3) THEN
      SkipFntdef(DVIcommand - fntdef1);
   ELSE
      (* DEBUG
         WriteLn;
         WriteString('Unexpected DVI command before first bop = ');
         WriteCard(DVIcommand); WriteLn;
         Halt(2);
      GUBED *)
      DVIErrorRoutine(DVIcatastrophe);
   END;
UNTIL DVIcommand = bop;
currbop := DVIoffset - 1;   (* position in DVI file of first bop *)
currDVIpage := 1;
END ReadFirstBop;

(******************************************************************************)

PROCEDURE SkipFntdef (which : CARDINAL);

(* Read past a fntdef command without interpreting it. *)

VAR dummy, a, l, i : CARDINAL;

BEGIN
CASE which OF   (* which = DVIcommand - fntdef1 *)
   0 : dummy := GetDVIByte() |
   1 : dummy := GetTwoDVIBytes() |
   2 : dummy := GetThreeDVIBytes() |
   3 : dummy := SignedDVIQuad()
END;
dummy := SignedDVIQuad();
dummy := SignedDVIQuad();
dummy := SignedDVIQuad();
a := GetDVIByte();        (* length of directory *)
l := GetDVIByte();        (* length of font name *)
FOR i := 0 TO l+a-1 DO
   dummy := GetDVIByte();
END;
END SkipFntdef;

(******************************************************************************)

PROCEDURE ReadNextBop;

(* We are currently positioned after an eop byte which we know is not the
   last.  This routine positions us after the next bop byte and updates
   currbop and currDVIpage.
*)

BEGIN
REPEAT   (* skip any nops and fntdefs *)
   DVIcommand := GetDVIByte();
   IF (DVIcommand = nop) OR (DVIcommand = bop) THEN
      (* do nothing *)
   ELSIF (DVIcommand >= fntdef1) AND (DVIcommand <= fntdef1+3) THEN
      SkipFntdef(DVIcommand - fntdef1);
   ELSE
      (* DEBUG
         WriteLn;
         WriteString('Unexpected DVI command between eop and bop = ');
         WriteCard(DVIcommand); WriteLn;
         Halt(2);
      GUBED *)
      DVIErrorRoutine(DVIcatastrophe);
   END;
UNTIL DVIcommand = bop;
currbop := DVIoffset - 1;   (* position in DVI file of this bop *)
INC(currDVIpage);
END ReadNextBop;

(******************************************************************************)

PROCEDURE ReadBopParameters;

(* We should now be positioned after the bop of desired page, so read
   the 10 TeX counters and update currTeXpage and prevbop.
   At the end of this routine we will be at the byte after currbop's parameters
   and ready to InterpretPage.
*)

VAR i : CARDINAL;

BEGIN
FOR i := 0 TO 9 DO
   currTeXpage[i] := SignedDVIQuad();
END;
prevbop := SignedDVIQuad();   (* position of previous bop in DVI file *)
END ReadBopParameters;

(******************************************************************************)

PROCEDURE MoveToDVIPage (n : CARDINAL);

(* Move to nth DVI page; n should be in 1..totalpages. *)

BEGIN
IF (n < 1) OR (n > totalpages) THEN   (* do nothing *)
   RETURN;
END;
IF n = 1 THEN
   (* Note that this test must come before next ELSIF so that we avoid any
      problems when currDVIpage initially = 0. *)
   ReadFirstBop;
(* We have removed the ELSIF code because it assumes InterpretPage is called
   after every MoveTo... routine (which PSDVI does NOT call when locating the
   first and final pages of a given subrange).
ELSIF n = currDVIpage + 1 THEN
   ReadNextBop;
*)
ELSE
   IF n < currDVIpage THEN
      currbop := prevbop;   (* start searching backwards from previous page *)
      DEC(currDVIpage);
   ELSIF n > currDVIpage THEN
      currbop := lastbop;   (* start searching backwards from last page *)
      currDVIpage := totalpages;
   ELSE
      (* n = currDVIpage so we'll just move back to currbop *)
   END;
   (* n is now <= currDVIpage so search by following backpointers *)
   LOOP
      IF n = currDVIpage THEN
         DVIoffset := currbop + 1;      (* move to byte after currbop *)
         EXIT;
      ELSE
         DVIoffset := currbop + 41;     (* move to location of backpointer *)
         currbop := SignedDVIQuad();    (* get location of previous page *)
         DEC(currDVIpage);
      END;
   END;
END;
ReadBopParameters;   (* update currTeXpage and prevbop *)
END MoveToDVIPage;

(******************************************************************************)

PROCEDURE MoveToTeXPage (VAR newTeXpage : TeXpageinfo)   (* in *)
                        : BOOLEAN;

(* Return TRUE iff the given TeX page exists.
   If so then we move to the lowest matching page.
*)

VAR savecurrbop, savecurrDVIpage : CARDINAL;
    nextbop : INTEGER;
    i : CARDINAL;
    atleastone : BOOLEAN;

BEGIN
(* save away current page and DVI position *)
savecurrDVIpage := currDVIpage;
IF currDVIpage <> 0 THEN           (* only if we've processed a page *)
   savecurrbop := currbop;
   (* note that curreop is saved in last InterpretPage *)
END;
(* search backwards through all DVI pages for lowest matching page *)
atleastone := FALSE;
nextbop := lastbop;
FOR i := totalpages TO 1 BY -1 DO
   DVIoffset := nextbop + 1;
   ReadBopParameters;              (* update currTeXpage and prevbop *)
   IF CurrMatchesNew(newTeXpage) THEN
      currbop := nextbop;
      currDVIpage := i;
      atleastone := TRUE;
   END;
   nextbop := prevbop;
END;
IF NOT atleastone THEN             (* no match, so restore currDVIpage *)
   currDVIpage := savecurrDVIpage;
   IF currDVIpage <> 0 THEN        (* restore page and positioning info *)
      currbop := savecurrbop;
      DVIoffset := currbop + 1;
      ReadBopParameters;           (* restore currTeXpage and prevbop *)
      DVIoffset := curreop + 1;
      (* we should now be after the eop byte of the original page *)
   END;
   RETURN FALSE;
ELSE                               (* we found lowest matching page *)
   DVIoffset := currbop + 1;
END;
ReadBopParameters;   (* update currTeXpage and prevbop *)
RETURN TRUE;
END MoveToTeXPage;

(******************************************************************************)

PROCEDURE CurrMatchesNew (VAR newTeXpage : TeXpageinfo) : BOOLEAN;

(* Return TRUE iff currTeXpage matches newTeXpage. *)

VAR i : [0..9];

BEGIN
WITH newTeXpage DO
   FOR i := 0 TO lastvalue DO
      IF present[i] AND (value[i] <> currTeXpage[i]) THEN
         RETURN FALSE;
      END;
   END;
END;
RETURN TRUE;
END CurrMatchesNew;


(*******************************************************************************
   DECLARATIONS FOR INTERPRETING A DVI PAGE

   The commands between the bop and eop bytes for a particular page need to be
   translated (based on the method used by DVITYPE) before we can determine the
   the position and shape of all rules on that page, as well as the position
   of all characters and which fonts they belong to.
*)

CONST
   (* Use symbolic names for the opcodes of DVI commands:                     *)
   setchar0 = 0;         (* setchar1..setchar127 = 1..127                     *)
   set1     = 128;       (* set2,set3,set4 = 129,130,131                      *)
   setrule  = 132;
   put1     = 133;       (* put2,put3,put4 = 134,135,136                      *)
   putrule  = 137;
   nop      = 138;
   bop      = 139;
   eop      = 140;
   push     = 141;
   pop      = 142;
   right1   = 143;  w0 = 147;  x0 = 152;  down1 = 157;  y0 = 161;  z0 = 166;
   right2   = 144;  w1 = 148;  x1 = 153;  down2 = 158;  y1 = 162;  z1 = 167;
   right3   = 145;  w2 = 149;  x2 = 154;  down3 = 159;  y2 = 163;  z2 = 168;
   right4   = 146;  w3 = 150;  x3 = 155;  down4 = 160;  y3 = 164;  z3 = 169;
                    w4 = 151;  x4 = 156;                y4 = 165;  z4 = 170;
   fntnum0  = 171;       (* fntnum1..fntnum63 = 172..234                      *)
   fnt1     = 235;       (* fnt2,fnt3,fnt4 = 236,237,238                      *)
   xxx1     = 239;       (* xxx2,xxx3,xxx4 = 240,241,242                      *)
   fntdef1  = 243;       (* fntdef2,fntdef3,fntdef4 = 244,245,246             *)
   pre      = 247;
   post     = 248;
   postpost = 249;
   (* undefined commands = 250..255 *)

   maxint       = 2147483647;        (* SYSDEP: 2^31 - 1                      *)
   maxstacksize = 100;               (* maximum stack size for state values   *)
   maxdrift     = 2;                 (* prevent hh & vv from drifting too far *)

VAR
   DVIcommand : [0..255];            (* holds next DVI command                *)
   maxstack,                         (* max pushes over pops in DVI file      *)
   num,                              (* DVI numerator                         *)
   den : CARDINAL;                   (* DVI denominator                       *)
   conv : REAL;                      (* converts DVI units to pixels          *)
   h, v,                             (* current pos on page in DVI units      *)
   w, x,                             (* horizontal increments in DVI units    *)
   y, z,                             (* vertical increments in DVI units      *)
   hh, vv,                           (* h and v in pixels                     *)
   hhh, vvv : INTEGER;               (* h and v rounded to nearest pixel      *)
   hstack, vstack,                   (* push down stacks for state values     *)
   wstack, xstack,
   ystack, zstack,
   hhstack, vvstack : ARRAY [0..maxstacksize-1] OF INTEGER;
   stackpos : [0..maxstacksize];     (* stacks empty when stackpos = 0,
                                        i.e., top of stacks = stackpos - 1    *)
   fontspace  : INTEGER;             (* used in DoRight and DoDown            *)
   thisrule   : ruleinfoptr;         (* temporary pointer to node in rulelist *)
   ruletail   : ruleinfoptr;         (* tail of rule information list         *)
   thischar   : charinfoptr;         (* temporary pointer to node in charlist *)

(******************************************************************************)

PROCEDURE SetConversionFactor (resolution, magnification : CARDINAL);

(* Client module must help calculate conv, the number of pixels per DVI unit. *)

BEGIN
conv := FLOAT(num)/254000.0 * FLOAT(resolution)/FLOAT(den) *
           FLOAT(magnification)/1000.0;
END SetConversionFactor;

(******************************************************************************)

PROCEDURE InterpretPage;

(* When this routine is called we are positioned after the bytes of a bop
   command (i.e., at currbop + 45).  At the end of this routine we will be
   positioned after the eop byte for the current page.  In between we carry
   out the important task of translating the DVI description of this page
   and filling in the various data structures exported by DVIReader.
*)

VAR param : INTEGER;

BEGIN
InitStateValues;
InitPage;
REPEAT
   DVIcommand := GetDVIByte();
   (* For efficiency reasons the most frequent commands should be tested 1st.
      The following order is the result of frequency testing on "typical"
      DVI files.  Note that the most frequent commands in the DVI file
      generated by TeX 1.3 for the Dec. 1983 LaTeX manual were:
      <set1, w0, right3, push/pop, x0, w3, y0, fntnum25, right2, fntnum31,
      down3, x2, right4, w2, x3, down4, z0, fntnum8, setrule, y3, etc.
   *)
   IF DVIcommand < set1       THEN DoSetChar(DVIcommand);   (* 0..127 *)
   ELSIF DVIcommand = w0      THEN DoRight(w);
   ELSIF DVIcommand = right3  THEN DoRight(SignedDVITrio());
   ELSIF DVIcommand = push    THEN DoPush;
   ELSIF DVIcommand = pop     THEN DoPop;
   ELSIF DVIcommand = x0      THEN DoRight(x);
   ELSIF DVIcommand = w3      THEN w := SignedDVITrio(); DoRight(w);
   ELSIF DVIcommand = y0      THEN DoDown(y);

   ELSIF (DVIcommand > z4) AND (DVIcommand < fnt1)   (* fntnum0..fntnum63 *)
                              THEN DoFont(DVIcommand - fntnum0);

   (* catch all the remaining movement commands *)
   ELSIF (DVIcommand > pop) AND (DVIcommand < fntnum0) THEN
      IF DVIcommand = right2     THEN DoRight(SignedDVIPair());
      ELSIF DVIcommand = right4  THEN DoRight(SignedDVIQuad());
      ELSIF DVIcommand = x2      THEN x := SignedDVIPair(); DoRight(x);
      ELSIF DVIcommand = x3      THEN x := SignedDVITrio(); DoRight(x);
      ELSIF DVIcommand = down3   THEN DoDown(SignedDVITrio());
      ELSIF DVIcommand = down4   THEN DoDown(SignedDVIQuad());
      ELSIF DVIcommand = w2      THEN w := SignedDVIPair(); DoRight(w);
      ELSIF DVIcommand = z0      THEN DoDown(z);
      ELSIF DVIcommand = y3      THEN y := SignedDVITrio(); DoDown(y);
      ELSIF DVIcommand = z3      THEN z := SignedDVITrio(); DoDown(z);
      ELSIF DVIcommand = down2   THEN DoDown(SignedDVIPair());
      (* the next DVI commands are used very rarely (by TeX 1.3 at least) *)
      ELSIF DVIcommand = w1      THEN w := SignedDVIByte(); DoRight(w);
      ELSIF DVIcommand = w4      THEN w := SignedDVIQuad(); DoRight(w);
      ELSIF DVIcommand = x1      THEN x := SignedDVIByte(); DoRight(x);
      ELSIF DVIcommand = x4      THEN x := SignedDVIQuad(); DoRight(x);
      ELSIF DVIcommand = y1      THEN y := SignedDVIByte(); DoDown(y);
      ELSIF DVIcommand = y2      THEN y := SignedDVIPair(); DoDown(y);
      ELSIF DVIcommand = y4      THEN y := SignedDVIQuad(); DoDown(y);
      ELSIF DVIcommand = z1      THEN z := SignedDVIByte(); DoDown(z);
      ELSIF DVIcommand = z2      THEN z := SignedDVIPair(); DoDown(z);
      ELSIF DVIcommand = z4      THEN z := SignedDVIQuad(); DoDown(z);
      ELSIF DVIcommand = right1  THEN DoRight(SignedDVIByte());
      ELSIF DVIcommand = down1   THEN DoDown(SignedDVIByte());
      ELSE  (* DEBUG
               (* will only occur if we've missed a movement command *)
               WriteLn; WriteString('Bug in InterpretPage!'); WriteLn; Halt(2);
            GUBED *)
            DVIErrorRoutine(DVIcatastrophe);
      END;

   ELSIF DVIcommand = setrule THEN DoSetRule(SignedDVIQuad(),SignedDVIQuad());
   ELSIF DVIcommand = putrule THEN DoPutRule(SignedDVIQuad(),SignedDVIQuad());

   ELSIF (DVIcommand >= put1) AND (DVIcommand <= put1+3) THEN
      CASE DVIcommand - put1 OF
         0 : DoPutChar(GetDVIByte()) |
         1 : DoPutChar(GetTwoDVIBytes()) |
         2 : DoPutChar(GetThreeDVIBytes()) |
         3 : DoPutChar(SignedDVIQuad())
      END;

   ELSIF (DVIcommand >= set1) AND (DVIcommand <= set1+3) THEN
      CASE DVIcommand - set1 OF
         0 : DoSetChar(GetDVIByte()) |
         1 : DoSetChar(GetTwoDVIBytes()) |
         2 : DoSetChar(GetThreeDVIBytes()) |
         3 : DoSetChar(SignedDVIQuad())
      END;

   ELSIF (DVIcommand >= fnt1) AND (DVIcommand <= fnt1+3) THEN
      CASE DVIcommand - fnt1 OF
         0 : DoFont(GetDVIByte()) |
         1 : DoFont(GetTwoDVIBytes()) |
         2 : DoFont(GetThreeDVIBytes()) |
         3 : DoFont(SignedDVIQuad())
      END;

   ELSIF (DVIcommand >= xxx1) AND (DVIcommand <= xxx1+3) THEN
      CASE DVIcommand - xxx1 OF
         0 : param := GetDVIByte() |
         1 : param := GetTwoDVIBytes() |
         2 : param := GetThreeDVIBytes() |
         3 : param := SignedDVIQuad()
      END;
      (* Pass current pixel position, number of bytes and
         byte grabbing function for client to use.
         We use IgnoreSpecial if client does not assign a procedure.
      *)
      SpecialRoutine(hh, vv, param, GetDVIByte);

   (* skip fntdef command since we've got this info from postamble *)
   ELSIF (DVIcommand >= fntdef1) AND (DVIcommand <= fntdef1+3)
                              THEN SkipFntdef(DVIcommand - fntdef1);

   ELSIF DVIcommand = nop     THEN (* do nothing *)
   ELSIF DVIcommand = eop     THEN (* do nothing *)
   ELSE
      (* DEBUG
         WriteLn;
         WriteString('Unexpected DVI command while interpreting page = ');
         WriteCard(DVIcommand); WriteLn;
         Halt(2);
      GUBED *)
      DVIErrorRoutine(DVIcatastrophe);
   END;
UNTIL DVIcommand = eop;
(* save position of eop byte for use in MoveToTeXPage *)
curreop := DVIoffset - 1;
IF stackpos <> 0 THEN
   (* DEBUG
      WriteString('Stack not empty at eop!'); WriteLn;
      Halt(2);
   GUBED *)
   DVIErrorRoutine(DVIcatastrophe);
END;
pageempty := (minhp = maxint) AND (minvp = maxint) AND
             (maxhp = -maxint) AND (maxvp = -maxint);   (* InitPage values *)
END InterpretPage;

(******************************************************************************)

PROCEDURE InitStateValues;

(* Initialize the state values and stack. *)

BEGIN
hh := hoffset;         (* 0 if no horizontal shift specified *)
vv := voffset;         (* 0 if no vertical shift specified *)
IF hoffset >= 0 THEN
   h :=   TRUNC(FLOAT(hoffset) / conv + 0.5);
ELSE
   h := - TRUNC(FLOAT(ABS(hoffset)) / conv + 0.5);
END;
IF voffset >= 0 THEN
   v :=   TRUNC(FLOAT(voffset) / conv + 0.5);
ELSE
   v := - TRUNC(FLOAT(ABS(voffset)) / conv + 0.5);
END;
w := 0; x := 0;
y := 0; z := 0;
stackpos  := 0;
fontspace := 0;        (* for DoRight and DoDown before a DoFont call *)
END InitStateValues;

(******************************************************************************)

PROCEDURE InitPage;

(* Initialize page structures so there are no fonts, no chars and no rules. *)

BEGIN
(* page edges will change if there is at least one char or rule on page *)
minhp := maxint;
minvp := maxint;
maxhp := -maxint;
maxvp := -maxint;
currfont := fontlist;
WHILE currfont <> NIL DO
   WITH currfont^ DO
      IF fontused THEN        (* only reset those fonts used in last page *)
         fontused := FALSE;
         totalchars := 0;
         (* deallocate char list completely; DoFont will allocate first node *)
         WHILE charlist <> NIL DO
            thischar := charlist;
            charlist := thischar^.nextchar;
            DISPOSE(thischar);
         END;
         chartail := NIL;
         (* pixel table remains allocated *)
      END;
      currfont := nextfont;
   END;
END;
currfont   := NIL;            (* current font is undefined at start of page *)
totalrules := 0;
(* deallocate rule information except for one node (for DoSet/PutRule) *)
WHILE rulelist <> ruletail DO
   thisrule := rulelist;
   rulelist := thisrule^.nextrule;
   DISPOSE(thisrule);
END;
rulelist^.rulecount := 0;     (* no rules in this node *)
rulelist^.nextrule  := NIL;
END InitPage;

(******************************************************************************)

PROCEDURE DoSetChar (ch : CARDINAL);

(* Add char info to current chartable, update our horizontal
   position on the page and check the page edges.
*)

BEGIN
WITH currfont^ DO
   IF ch > maxTeXchar THEN
      DVIErrorRoutine(DVIbadchar);
      RETURN;                             (* ignore ch *)
   END;
   WITH chartail^ DO
      IF charcount = chartablesize THEN   (* allocate a new chartable *)
         NEW(nextchar);                   (* add new node to end of char list *)
         nextchar^.charcount := 0;        (* reset charcount *)
         nextchar^.nextchar  := NIL;
         chartail := nextchar;
      END;
   END;
   WITH chartail^ DO                      (* may be new chartable *)
      WITH chartable[charcount] DO
         hp := hh;
         vp := vv;
         code := ch;
      END;
      WITH pixelptr^[ch] DO
         (* do page edges increase? *)
         IF vv - yo < minvp THEN minvp := vv - yo END;
         IF hh - xo < minhp THEN minhp := hh - xo END;
         IF vv + (ht - yo - 1) > maxvp THEN maxvp := vv + (ht - yo - 1) END;
         IF hh + (wd - xo - 1) > maxhp THEN maxhp := hh + (wd - xo - 1) END;
         (* the above checks ensure that page edges include all black
            pixels in glyph, but we also want to include reference point *)
         IF hh < minhp THEN minhp := hh END;
         IF vv < minvp THEN minvp := vv END;
         IF hh > maxhp THEN maxhp := hh END;
         IF vv > maxvp THEN maxvp := vv END;
         (* add pixel width calculated in PixelTableRoutine *)
         hh := hh + pwidth;
         (* use hhh and maxdrift to prevent hh drifting too far from h *)
         hhh := PixelRound(h + dwidth);
         IF ABS(hhh - hh) > maxdrift THEN
            IF hhh > hh THEN
               hh := hhh - maxdrift;
            ELSE
               hh := hhh + maxdrift;
            END;
         END;
         (* add DVI width calculated in PixelTableRoutine *)
         h := h + dwidth;
      END;
      INC(totalchars);
      INC(charcount);
   END;
END;
END DoSetChar;

(******************************************************************************)

PROCEDURE DoPutChar (ch : CARDINAL);

(* Exactly the same as DoSetChar, but we DON'T update the horizontal
   position on the page.  (We still have to check page edges.)
*)

BEGIN
WITH currfont^ DO
   IF ch > maxTeXchar THEN
      DVIErrorRoutine(DVIbadchar);
      RETURN;                             (* ignore ch *)
   END;
   WITH chartail^ DO
      IF charcount = chartablesize THEN   (* allocate a new chartable *)
         NEW(nextchar);                   (* add new node to end of char list *)
         nextchar^.charcount := 0;        (* reset charcount *)
         nextchar^.nextchar  := NIL;
         chartail := nextchar;
      END;
   END;
   WITH chartail^ DO                      (* may be new chartable *)
      WITH chartable[charcount] DO
         hp := hh;
         vp := vv;
         code := ch;
      END;
      WITH pixelptr^[ch] DO
         (* do page edges increase? *)
         IF vv - yo < minvp THEN minvp := vv - yo END;
         IF hh - xo < minhp THEN minhp := hh - xo END;
         IF vv + (ht - yo - 1) > maxvp THEN maxvp := vv + (ht - yo - 1) END;
         IF hh + (wd - xo - 1) > maxhp THEN maxhp := hh + (wd - xo - 1) END;
         (* the above checks ensure that page edges include all black
            pixels in glyph, but we also want to include reference point *)
         IF hh < minhp THEN minhp := hh END;
         IF vv < minvp THEN minvp := vv END;
         IF hh > maxhp THEN maxhp := hh END;
         IF vv > maxvp THEN maxvp := vv END;
      END;
      INC(totalchars);
      INC(charcount);
   END;
END;
END DoPutChar;

(******************************************************************************)

PROCEDURE PixelRound (DVIunits : INTEGER) : INTEGER;

(* Return the nearest number of pixels in the given DVI dimension. *)

BEGIN
IF DVIunits > 0 THEN
   RETURN   TRUNC(conv * FLOAT(DVIunits) + 0.5);
ELSE
   RETURN - TRUNC(conv * FLOAT(ABS(DVIunits)) + 0.5);
END;
END PixelRound;

(******************************************************************************)

PROCEDURE DoPush;

(* Push state values onto stack.
   No need to test for stack overflow since we compare maxstack and
   maxstacksize in ProcessPostamble.
*)

BEGIN
hstack[stackpos] := h;   vstack[stackpos] := v;
wstack[stackpos] := w;   xstack[stackpos] := x;
ystack[stackpos] := y;   zstack[stackpos] := z;
hhstack[stackpos] := hh; vvstack[stackpos] := vv;
INC(stackpos);   (* stackpos = next vacant position in stacks *)
END DoPush;

(******************************************************************************)

PROCEDURE DoPop;

(* Pop state values from top of stack. *)

BEGIN
(* DEBUG
   IF stackpos = 0 THEN
      WriteString('Stack empty!'); WriteLn;
      Halt(2);
   END;
GUBED *)
DEC(stackpos);
h := hstack[stackpos];   v := vstack[stackpos];
w := wstack[stackpos];   x := xstack[stackpos];
y := ystack[stackpos];   z := zstack[stackpos];
hh := hhstack[stackpos]; vv := vvstack[stackpos];
END DoPop;

(******************************************************************************)

PROCEDURE DoRight (amount : INTEGER);

(* Move the reference point horizontally by given amount (usually +ve).
   When the amount is small, like a kern, hh changes
   by rounding the amount; but when the amount is large, hh changes by rounding
   the true position h so that accumulated rounding errors disappear.
*)

BEGIN
IF (amount < fontspace) AND (amount > -4 * fontspace) THEN
   hh  := hh + PixelRound(amount);
   (* use hhh and maxdrift to prevent hh drifting too far from h *)
   hhh := PixelRound(h + amount);
   IF ABS(hhh - hh) > maxdrift THEN
      IF hhh > hh THEN
         hh := hhh - maxdrift;
      ELSE
         hh := hhh + maxdrift;
      END;
   END;
ELSE
   hh := PixelRound(h + amount);
END;
h := h + amount;
END DoRight;

(******************************************************************************)

PROCEDURE DoDown (amount : INTEGER);

(* Move the reference point vertically by given amount (usually +ve).
   Rounding is done similarly to DoRight but with the threshold between
   small and large amounts increased by a factor of 5.
*)

BEGIN
IF ABS(amount) < 5 * fontspace THEN
   vv := vv + PixelRound(amount);
   (* use vvv and maxdrift to prevent vv drifting too far from v *)
   vvv := PixelRound(v + amount);
   IF ABS(vvv - vv) > maxdrift THEN
      IF vvv > vv THEN
         vv := vvv - maxdrift;
      ELSE
         vv := vvv + maxdrift;
      END;
   END;
ELSE
   vv := PixelRound(v + amount);
END;
v := v + amount;
END DoDown;

(******************************************************************************)

PROCEDURE DoSetRule (height, width : INTEGER);

(* Add rule information to current ruletable, update page edges, h and hh
   (but only if width and height are > 0).
*)

BEGIN
IF (height > 0) AND (width > 0) THEN
   WITH ruletail^ DO
      IF rulecount = ruletablesize THEN   (* allocate a new ruletable *)
         NEW(nextrule);                   (* add new node to end of rule list *)
         nextrule^.rulecount := 0;        (* reset rulecount *)
         nextrule^.nextrule  := NIL;
         ruletail := nextrule;
      END;
   END;
   WITH ruletail^ DO                      (* may be new ruletable *)
      WITH ruletable[rulecount] DO
         hp := hh;
         vp := vv;
         wd := RulePixels(width);
         ht := RulePixels(height);
         (* do page edges increase? *)
         IF vv - (ht - 1) < minvp THEN minvp := vv - (ht - 1) END;
         IF hh + (wd - 1) > maxhp THEN maxhp := hh + (wd - 1) END;
         (* ref pt of rule is bottom left black pixel *)
         IF vv > maxvp THEN maxvp := vv END;
         IF hh < minhp THEN minhp := hh END;
         hh := hh + wd;
         (* use hhh and maxdrift to prevent hh drifting too far from h *)
         hhh := PixelRound(h + width);
         IF ABS(hhh - hh) > maxdrift THEN
            IF hhh > hh THEN
               hh := hhh - maxdrift;
            ELSE
               hh := hhh + maxdrift;
            END;
         END;
         h := h + width;
      END;
      INC(totalrules);
      INC(rulecount);
   END;
END;
END DoSetRule;

(******************************************************************************)

PROCEDURE DoPutRule (height, width : INTEGER);

(* Exactly the same as DoSetRule, but we DON'T update the horizontal
   position on the page.  (We still have to check page edges.)
*)

BEGIN
IF (height > 0) AND (width > 0) THEN
   WITH ruletail^ DO
      IF rulecount = ruletablesize THEN   (* allocate a new ruletable *)
         NEW(nextrule);                   (* add new node to end of rule list *)
         nextrule^.rulecount := 0;        (* reset rulecount *)
         nextrule^.nextrule := NIL;
         ruletail := nextrule;
      END;
   END;
   WITH ruletail^ DO                      (* may be new ruletable *)
      WITH ruletable[rulecount] DO
         hp := hh;
         vp := vv;
         wd := RulePixels(width);
         ht := RulePixels(height);
         (* do page edges increase? *)
         IF vv - (ht - 1) < minvp THEN minvp := vv - (ht - 1) END;
         IF hh + (wd - 1) > maxhp THEN maxhp := hh + (wd - 1) END;
         (* ref pt of rule is bottom left black pixel *)
         IF vv > maxvp THEN maxvp := vv END;
         IF hh < minhp THEN minhp := hh END;
      END;
      INC(totalrules);
      INC(rulecount);
   END;
END;
END DoPutRule;

(******************************************************************************)

PROCEDURE RulePixels (DVIunits : INTEGER) : INTEGER;

(* Return the number of pixels in the given height or width of a rule
   using the method recommended in DVITYPE.
*)

VAR n : INTEGER;

BEGIN
n := TRUNC(conv * FLOAT(DVIunits));
IF FLOAT(n) < conv * FLOAT(DVIunits) THEN RETURN n + 1 ELSE RETURN n END;
END RulePixels;

(******************************************************************************)

PROCEDURE DoFont (externf : INTEGER);

(* Search font list for externf, setting currfont and fontspace.
   If this is the first time we've seen this font (on current page) then
   we need to allocate the first chartable.
   If this is the first time we've seen this font used at all then we
   allocate a pixeltable and call client routine to fill it in.
*)

BEGIN
currfont := fontlist;
WHILE (currfont <> NIL) AND (currfont^.fontnum <> externf) DO
   currfont := currfont^.nextfont;
END;
IF currfont = NIL THEN
   (* DEBUG
      WriteLn; WriteString('Failed to find font #'); WriteInt(externf);
      WriteLn; Halt(2);
   GUBED *)
   DVIErrorRoutine(DVIcatastrophe);
END;
WITH currfont^ DO
   IF fontused THEN
      (* do nothing since we've already used this font on this page *)
   ELSE
      fontused := TRUE;
      NEW(charlist);           (* allocate first chartable *)
      WITH charlist^ DO
         charcount := 0;       (* for DoSet/PutChar *)
         nextchar  := NIL;     (* this node is also last *)
      END;
      chartail := charlist;
      IF pixelptr = NIL THEN   (* first time we've seen this font requested *)
         NEW(pixelptr);
         PixelTableRoutine;    (* call client routine to build pixel table *)
      END;
   END;
   fontspace  := scaledsize DIV 6;
   (* See DVITYPE; a 3-unit thin space.
      Note that a thin space is 1/6 of a quad, where a quad is
      1 em in the current font and usually equals the design size.
   *)
END;
END DoFont;

(******************************************************************************)

PROCEDURE IgnoreSpecial(xpos, ypos,                        (* in *)
                        specialbytes : INTEGER;            (* in *)
                        GetNextByte  : GetByteFunction);   (* in *)

(* Default SpecialRoutine simply skips bytes given to TeX's \special command. *)

VAR i, unused : INTEGER;

BEGIN
FOR i := 1 TO specialbytes DO
   unused := GetNextByte();
END;
END IgnoreSpecial;

(******************************************************************************)

PROCEDURE SortFonts (VAR unusedlist : fontinfoptr);   (* out *)

(* Sort fontlist in order of ascending totalchars.
   Fonts with least characters can then be accessed first.
   Since the number of fonts used on a typical page is quite small, a simple
   sorting algorithm should be good enough.  Note that unused fonts are moved
   to the end of the list and unusedlist points to the first such node.
*)

VAR newfontlist, prevfont, largest, prevlargest : fontinfoptr;
    mostchars : CARDINAL;

BEGIN
newfontlist  := NIL;
(* go thru fontlist once and move all unused fonts to head of newfontlist *)
prevfont := NIL;
currfont := fontlist;
WHILE currfont <> NIL DO
   WITH currfont^ DO
      IF fontused THEN
         prevfont := currfont;      (* remember previous node *)
         currfont := nextfont;
      ELSE
         (* move node from fontlist to head of newfontlist
            and don't change prevfont
         *)
         IF prevfont = NIL THEN
            fontlist := nextfont;   (* remove first node in fontlist *)
            nextfont := newfontlist;
            newfontlist := currfont;
            currfont := fontlist;
         ELSE
            prevfont^.nextfont := nextfont;
            nextfont := newfontlist;
            newfontlist := currfont;
            currfont := prevfont^.nextfont;
         END;
      END;
   END;
END;
(* unusedlist will be last unused font moved to newfontlist.  It will be NIL
   if either fontlist is NIL or all fonts are used.
*)
unusedlist := newfontlist;
(* Now go thru fontlist repeatedly moving node with max totalchars to
   head of newfontlist until fontlist is exhausted.
*)
WHILE fontlist <> NIL DO
   prevfont := NIL;
   currfont := fontlist;
   prevlargest := NIL;
   largest     := fontlist;
   mostchars   := 0;
   WHILE currfont <> NIL DO   (* search for largest totalchars *)
      WITH currfont^ DO
         IF totalchars > mostchars THEN
            prevlargest := prevfont;
            largest     := currfont;
            mostchars   := totalchars;
         END;
         prevfont := currfont;
         currfont := nextfont;
      END;
   END;
   (* move largest node from fontlist to head of newfontlist *)
   WITH largest^ DO
      IF prevlargest = NIL THEN
         fontlist := nextfont;   (* remove first node in fontlist *)
      ELSE
         prevlargest^.nextfont := nextfont;
      END;
      nextfont := newfontlist;
      newfontlist := largest;
   END;
END;
fontlist := newfontlist;   (* used fonts now sorted and unused fonts at end *)
END SortFonts;

(******************************************************************************)

PROCEDURE CloseDVIFile;

(* Close the currently open DVI file and deallocate dynamic data structures. *)

BEGIN
status := SYS$DELTVA(ADR(vas),ADR(vas),0);
IF NOT ODD(status) THEN
   (* DEBUG
      WriteString('SYS$DELTVA failed! status='); WriteCard(status);
      WriteLn; Halt(2);
   GUBED *)
   DVIErrorRoutine(DVIcatastrophe);
END;
status := SYS$DASSGN(channel);
IF NOT ODD(status) THEN
   (* DEBUG
      WriteString('SYS$DASSGN failed! status='); WriteCard(status);
      WriteLn; Halt(2);
   GUBED *)
   DVIErrorRoutine(DVIcatastrophe);
END;
WHILE fontlist <> NIL DO
   currfont := fontlist;
   WITH currfont^ DO
      WHILE charlist <> NIL DO   (* deallocate char list *)
         thischar := charlist;
         charlist := thischar^.nextchar;
         DISPOSE(thischar);
      END;
      IF pixelptr <> NIL THEN
         DISPOSE(pixelptr);      (* deallocate pixel table *)
      END;
      fontlist := nextfont;
   END;
   DISPOSE(currfont);            (* deallocate font information *)
END;
(* Deallocate rule information except for one node (in case client opens
   another DVI file).
*)
WHILE rulelist <> ruletail DO
   thisrule := rulelist;
   rulelist := thisrule^.nextrule;
   DISPOSE(thisrule);
END;
END CloseDVIFile;

(******************************************************************************)

BEGIN
totalrules := 0;
NEW(rulelist);                     (* for first InitPage *)
ruletail := rulelist;              (* ditto *)
fontlist := NIL;                   (* safer for CloseDVIFile *)
SpecialRoutine := IgnoreSpecial;   (* client can reassign *)
END DVIReader.