summaryrefslogtreecommitdiff
path: root/dviware/psprint/unix/fontreader.p
blob: c52c214a1e8e433b7b174b2a91ad048da0d717ec (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
(* FontReader implements the routines for reading character metric and
   bitmap information from PK files, or from TFM files for PostScript fonts.
*)

#include 'globals.h';
#include 'files.h';
#include 'options.h';
#include 'dvireader.h';
#include 'fontreader.h';
#include 'pswriter.h';     (* for PSfile and NewBitmapFont *)

TYPE
   BITSET = SET OF 0..31;

   (* SYSDEP: The following variant record is needed because
      Pyramid Pascal does not provide type coercion.
      Note that we couldn't overlay INTEGER and BITSET because
      of the crazy storage scheme used to represent a set of 0..31
      where the bit order within a word is 7..0 15..8 23..16 31..24!
   *)

   bytes_or_bits = RECORD
                   CASE b : BOOLEAN OF
                      TRUE  : (ch   : PACKED ARRAY [0..3] OF CHAR);
                      FALSE : (bits : BITSET);
                   END;

VAR
   PTfile : integer;                   (* PK/TFM file descriptor              *)
   PToffset : INTEGER;                 (* current byte offset in PTfile       *)
   currPTbuff : INTEGER;               (* starting byte offset in buffer      *)
   PTbuffer : buffer;                  (* input buffer                        *)
   psprefixlen,                        (* length of psprefix string           *)
   fontdirlen : INTEGER;               (* length of fontdir string            *)
   hexdigs : ARRAY [0..15] OF CHAR;    (* 0..9ABCDEF for LoadBitmap           *)
   gpower : ARRAY [0..32] OF BITSET;   (* 0,1,11,111,1111,...                 *)
   turnon : BOOLEAN;                   (* is current run black?               *)
   dynf,                               (* dynamic packing variable            *)
   repeatcount,                        (* times to repeat the next row        *)
   bitweight : INTEGER;                (* for bits or nybbles from inputbyte  *)
   inputbyte : bytes_or_bits;          (* the current input byte              *)
   lf, lh, bc, ec, nw, nh : INTEGER;   (* TFM file data                       *)
   TFMinfo     : ARRAY [0..255] OF
                    RECORD
                       wdindex, htindex, dpindex : INTEGER;
                    END;
   charmetrics : ARRAY [0..255] OF
                    RECORD
                       width, height, depth : ARRAY [0..3] OF INTEGER;
                    END;

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

PROCEDURE BuildTFMSpec (fontptr : fontinfoptr);

(* Build a complete TFM file specification in fontptr^.fontspec.
   This will only be done once per font; fontspeclen will no longer be 0.
   fontptr^.fontexists becomes TRUE if the file can be opened.
*)

LABEL 999;

VAR f, result, i, nxt : INTEGER;

BEGIN
WITH fontptr^ DO BEGIN
   i := 0;
   IF fontarealen > 0 THEN BEGIN
      nxt := fontarealen;
      REPEAT
         fontspec[i] := fontarea[i];   (* start fontspec with fontarea *)
         i := i + 1;
      UNTIL (i = nxt) OR (i > maxfontspec);
   END
   ELSE BEGIN
      nxt := Len(tfmdir);              (* assume > 0 *)
      REPEAT
         fontspec[i] := tfmdir[i];     (* start fontspec with tfmdir *)
         i := i + 1;
      UNTIL (i = nxt) OR (i > maxfontspec);
   END;
   IF nxt >= maxfontspec THEN BEGIN
      fontspeclen := maxfontspec;
      goto 999;                        (* fontspec truncated *)
   END;
   (* nxt is current length of fontspec; append fontname.tfm *)
   i := 0;
   WHILE (i < fontnamelen) AND (nxt < maxfontspec) DO BEGIN
      fontspec[nxt] := fontname[i];    (* append fontname *)
      i := i + 1;
      nxt := nxt + 1;
   END;
   IF nxt + 4 <= maxfontspec THEN BEGIN      (* append .tfm *)
      fontspec[nxt] := '.'; nxt := nxt + 1;
      fontspec[nxt] := 't'; nxt := nxt + 1;
      fontspec[nxt] := 'f'; nxt := nxt + 1;
      fontspec[nxt] := 'm'; nxt := nxt + 1;
   END
   ELSE BEGIN
      fontspeclen := maxfontspec;
      goto 999;                        (* fontspec truncated *)
   END;
   fontspeclen := nxt;
   IF fontspeclen < maxstring THEN fontspec[fontspeclen] := CHR(0);
   f := open(fontspec,O_RDONLY,0);     (* try to open file *)
   IF fontspeclen < maxstring THEN fontspec[fontspeclen] := ' ';
   IF f >= 0 THEN BEGIN
      result := close(f);
      fontexists := TRUE;              (* fontspec exists *)
   END;
END;
999:
END; (* BuildTFMSpec *)

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

FUNCTION CompleteFontSpec (fontptr : fontinfoptr;
                           nxt : INTEGER;
                           fontsizelen : INTEGER;
                           VAR firstn : INTEGER) : BOOLEAN;

(* Return TRUE if we can append "fontname.n...npk" to fontspec.
   Such a scheme is used in the latest TeX distributions.
*)

LABEL 999;

VAR i : INTEGER;

BEGIN
WITH fontptr^ DO BEGIN
   i := 0;
   WHILE (i < fontnamelen) AND (nxt < maxfontspec) DO BEGIN
      fontspec[nxt] := fontname[i];                    (* append fontname *)
      i := i + 1;
      nxt := nxt + 1;
   END;
   firstn := nxt + 1;                                  (* position of 1st n *)
   IF nxt + fontsizelen + 2 < maxfontspec THEN BEGIN
      fontspec[nxt] := '.';
      nxt := nxt + fontsizelen + 1;                    (* skip n...n *)
      fontspec[nxt] := 'p';                            (* append pk *)
      nxt := nxt + 1;
      fontspec[nxt] := 'k';
      nxt := nxt + 1;
   END
   ELSE BEGIN
      fontspeclen := maxfontspec;
      CompleteFontSpec := FALSE;
      goto 999;                                        (* fontspec truncated *)
   END;
   fontspeclen := nxt;
   IF nxt < maxfontspec THEN fontspec[nxt] := ' ';     (* terminate string *)
   CompleteFontSpec := TRUE;
END;
999:
END; (* CompleteFontSpec *)

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

PROCEDURE BuildFontSpec (fontptr : fontinfoptr; VAR firstn, lastn : INTEGER);

(* Build a complete file specification in fontptr^.fontspec.
   This will only be done once per font; fontspeclen will no longer be 0.
   fontptr^.fontexists becomes TRUE if the file can be opened.
*)

LABEL 888, 999;

VAR f, result, i, j, nxt, fontsize, tempsize, tempsizelen : INTEGER;

BEGIN
WITH fontptr^ DO BEGIN
   (* first check for a PostScript font; following code will set psfont to TRUE
      if psprefixlen = 0 --- ALL fonts will be considered PostScript fonts
   *)
   psfont := TRUE;
   i := 0;
   WHILE TRUE DO BEGIN
      IF i = psprefixlen THEN goto 888;
      IF Cap(fontname[i]) <> Cap(psprefix[i]) THEN BEGIN
         psfont := FALSE;
         goto 888;
      END;
      i := i + 1;
   END;
   888:
   IF psfont THEN BEGIN
      BuildTFMSpec(fontptr);           (* build TFM file spec *)
      goto 999;
   END;
   i := 0;
   nxt := fontdirlen;
   REPEAT
      fontspec[i] := fontdir[i];       (* start fontspec with fontdir *)
      i := i + 1;
   UNTIL (i = nxt) OR (i > maxfontspec);
   IF nxt >= maxfontspec THEN BEGIN
      fontspeclen := maxfontspec;
      goto 999;                        (* fontspec truncated *)
   END;
   fontsize := TRUNC( mag * (scaledsize / designsize)
                          * (resolution / 1000.0) + 0.5 );
   IF fontsize = 0 THEN
      fontsize := fontsize + 1;        (* allow for subtracting 1 *)
   tempsize := fontsize;
   i := 1;
   WHILE TRUE DO BEGIN
      (* Complete rest of fontspec starting at nxt
         and return the position of first digit for fontsize.
         We have to try fontsize +/- 1 before giving up because
         rounding problems can occur in the above fontsize calculation.
      *)
      j := tempsize;
      tempsizelen := 0;
      WHILE j > 0 DO BEGIN
         tempsizelen := tempsizelen + 1;
         j := j DIV 10;
      END;
      IF NOT CompleteFontSpec(fontptr, nxt, tempsizelen, firstn) THEN
         goto 999;                     (* fontspec truncated *)
      lastn := firstn + tempsizelen - 1;
      (* put tempsize into fontspec[firstn..lastn] *)
      FOR j := lastn DOWNTO firstn DO BEGIN
         fontspec[j] := CHR(ORD('0') + (tempsize MOD 10));
         tempsize := tempsize DIV 10;
      END;
      IF i > 3 THEN                    (* original fontsize has been restored *)
         goto 999;                     (* could not open fontspec *)
      IF fontspeclen < maxstring THEN fontspec[fontspeclen] := CHR(0);
      f := open(fontspec,O_RDONLY,0);  (* try to open file *)
      IF fontspeclen < maxstring THEN fontspec[fontspeclen] := ' ';
      IF f >= 0 THEN BEGIN
         result := close(f);
         fontexists := TRUE;           (* fontspec exists *)
         goto 999;
      END
      ELSE IF i = 1 THEN
         tempsize := fontsize - 1      (* try fontsize-1 *)
      ELSE IF i = 2 THEN
         tempsize := fontsize + 1      (* try fontsize+1 *)
      ELSE
         tempsize := fontsize;         (* restore original fontsize *)
      i := i + 1;
   END;
END;
999:
END; (* BuildFontSpec *)

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

FUNCTION  OpenFontFile (VAR name : string) : BOOLEAN;

(* Return TRUE if given file can be opened.
   Only one font file will be open at any given time.
*)

LABEL 888;

VAR length : integer;

BEGIN
currPTbuff := -1;   (* impossible value for first GetPTByte *)
length := 0;
WHILE length < maxstring DO BEGIN
   IF name[length] = ' ' THEN goto 888;
   length := length + 1;
END;
888:
IF length < maxstring THEN name[length] := CHR(0);   (* terminate with NULL *)
PTfile := open(name, O_RDONLY, 0);
IF length < maxstring THEN name[length] := ' ';      (* restore space *)
OpenFontFile := PTfile >= 0;
END; (* OpenFontFile *)

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

PROCEDURE CloseFontFile;

(* Close the currently open font file. *)

VAR result : integer;

BEGIN
result := close(PTfile);
END; (* CloseFontFile *)

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

FUNCTION GetPTByte : INTEGER;

(* Returns the value (unsigned) of the byte at PToffset and
   advances PToffset for the next GetPTByte.
*)

VAR buffstart, result : INTEGER;

BEGIN
buffstart := (PToffset DIV bufflen) * bufflen;   (* 0, bufflen, 2*bufflen... *)
IF buffstart <> currPTbuff THEN BEGIN
   currPTbuff := buffstart;
   result := lseek(PTfile, buffstart, 0);
   { DEBUG
     IF result <> buffstart THEN BEGIN
        writeln('Lseek failed in GetPTByte!'); exit(1);
     END;
   GUBED }
   result := read(PTfile, PTbuffer, bufflen);
   { DEBUG
     IF result = -1 THEN BEGIN
        writeln('Read failed in GetPTByte!'); exit(1);
     END;
   GUBED }
END;
GetPTByte := ORD(PTbuffer[PToffset - buffstart]);
PToffset := PToffset + 1;
END; (* GetPTByte *)

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

FUNCTION SignedPTByte : INTEGER;        (* the next byte, signed *)

VAR b : INTEGER;

BEGIN
b := GetPTByte;
IF b < 128 THEN
   SignedPTByte := b
ELSE
   SignedPTByte := b - 256;
END; (* SignedPTByte *)

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

FUNCTION GetTwoPTBytes : INTEGER;       (* the next 2 bytes, unsigned *)

VAR a, b : INTEGER;

BEGIN
a := GetPTByte;
b := GetPTByte;
GetTwoPTBytes := a * 256 + b;
END; (* GetTwoPTBytes *)

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

FUNCTION SignedPTPair : INTEGER;        (* the next 2 bytes, signed *)

VAR a, b : INTEGER;

BEGIN
a := GetPTByte;
b := GetPTByte;
IF a < 128 THEN
   SignedPTPair := a * 256 + b
ELSE
   SignedPTPair := (a - 256) * 256 + b;
END; (* SignedPTPair *)

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

FUNCTION GetThreePTBytes : INTEGER;     (* the next 3 bytes, unsigned *)

VAR a, b, c : INTEGER;

BEGIN
a := GetPTByte;
b := GetPTByte;
c := GetPTByte;
GetThreePTBytes := (a * 256 + b) * 256 + c;
END; (* GetThreePTBytes *)

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

FUNCTION SignedPTQuad : INTEGER;        (* the next 4 bytes, signed *)


TYPE int_or_bytes = RECORD
                    CASE b : BOOLEAN OF
                       TRUE  : (int : INTEGER);
                       FALSE : (byt : PACKED ARRAY [0..3] OF CHAR);
                    END;

VAR w : int_or_bytes;

BEGIN
WITH w DO BEGIN
   w.byt[0] := CHR(GetPTByte);
   w.byt[1] := CHR(GetPTByte);
   w.byt[2] := CHR(GetPTByte);
   w.byt[3] := CHR(GetPTByte);
END;
SignedPTQuad := w.int;
END; (* SignedPTQuad *)

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

FUNCTION GetNyb : INTEGER;

(* Return next nybble in PK file. *)

BEGIN
IF bitweight = 0 THEN BEGIN
   (* SYSDEP: Pyramid Pascal stores bits 7..0 in the LEFT
      byte of a 4-byte BITSET word. *)
   inputbyte.ch[0] := CHR(GetPTByte);
   bitweight := 16;                         (* for next call of GetNyb *)
   GetNyb := ORD(inputbyte.ch[0]) DIV 16;   (* high nybble *)
END
ELSE BEGIN
   bitweight := 0;                          (* for next call of GetNyb *)
   GetNyb := ORD(inputbyte.ch[0]) MOD 16;   (* low nybble *)
END;
END; (* GetNyb *)

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

FUNCTION PackedNum : INTEGER;

(* Return next run count using algorithm given in section 23 of PKtype.
   A possible side-effect is to set the global repeatcount value used
   to duplicate the current row.
*)

VAR i, j : INTEGER;

BEGIN
i := GetNyb;
IF i = 0 THEN BEGIN
   REPEAT j := GetNyb; i := i + 1 UNTIL j <> 0;
   WHILE i > 0 DO BEGIN j := j * 16 + GetNyb; i := i - 1 END;
   PackedNum := j - 15 + (13 - dynf) * 16 + dynf;
END
ELSE IF i <= dynf THEN
   PackedNum := i
ELSE IF i < 14 THEN
   PackedNum := (i - dynf - 1) * 16 + GetNyb + dynf + 1
ELSE BEGIN
   IF i = 14 THEN
      repeatcount := PackedNum   (* recursive *)
   ELSE
      repeatcount := 1;          (* nybble = 15 *)
   PackedNum := PackedNum;       (* recursive *)
END;
END; (* PackedNum *)

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

PROCEDURE LoadBitmap (fontptr : fontinfoptr; code : INTEGER);

(* Output PostScript character definition using bitmap info at mapadr
   in currently open PK file.
*)

CONST maxhexline = 72;                 (* keep even and < 80 *)

VAR
   hexline : PACKED ARRAY [1..maxhexline] OF CHAR;
   hexcount,                           (* current hexline length *)
   i, j, flagbyte, bitpos, bytesperrow,
   rowsleft, hbit, count, rp : INTEGER;
   byte : bytes_or_bits;               (* we'll only consider bits 0..7 *)
   row : ARRAY [0..400] OF CHAR;       (* maximum glyph width = 3200 bits *)

BEGIN
WITH fontptr^.pixelptr^[code] DO BEGIN
bytesperrow := (wd + 7) DIV 8;         (* bytes in one row *)
PToffset := mapadr;                    (* mapadr = flagbyte offset in PK file *)
flagbyte := GetPTByte;                 (* assume < 240 *)
dynf := flagbyte DIV 16;
turnon := (flagbyte MOD 16) >= 8;      (* is 1st pixel black? *)
flagbyte := flagbyte MOD 8;            (* value of bottom 3 bits *)
IF flagbyte < 4 THEN                   (* skip short char preamble *)
   PToffset := PToffset + 10
ELSE IF flagbyte < 7 THEN              (* skip extended short char preamble *)
   PToffset := PToffset + 16
ELSE                                   (* skip long char preamble *)
   PToffset := PToffset + 36;
hexline[1] := '[';                     (* start of hex string *)
hexline[2] := '<';
hexcount  := 2;                        (* chars in current hexline *)
bitweight := 0;                        (* to get 1st inputbyte *)
IF dynf = 14 THEN BEGIN
   (* raster info is a string of bits in the next (wd * ht + 7) DIV 8 bytes *)
   FOR i := 1 TO ht DO BEGIN
      byte.bits := [];                               (* set all bits to 0 *)
      bitpos := 7;                                   (* leftmost bit *)
      FOR j := 1 TO wd DO BEGIN
         IF bitweight = 0 THEN BEGIN
            inputbyte.ch[0] := CHR(GetPTByte);
            bitweight := 8;
         END;
         bitweight := bitweight - 1;                 (* 7..0 *)
         IF bitweight IN inputbyte.bits THEN
            byte.bits := byte.bits + [bitpos];       (* include bitpos *)
         IF bitpos > 0 THEN
            bitpos := bitpos - 1                     (* next bit *)
         ELSE BEGIN
            (* SYSDEP: Pyramid Pascal stores bits 7..0 in the LEFT
               byte of a 4-byte BITSET word. *)
            hexcount := hexcount + 1;
            hexline[hexcount] := hexdigs[ ORD(byte.ch[0]) DIV 16 ];
            hexcount := hexcount + 1;
            hexline[hexcount] := hexdigs[ ORD(byte.ch[0]) MOD 16 ];
            IF hexcount = maxhexline THEN BEGIN
               writeln(PSfile,hexline:hexcount);
               hexcount := 0;
            END;
            byte.bits := [];
            bitpos := 7;
         END;
      END;
      IF bitpos < 7 THEN BEGIN
         hexcount := hexcount + 1;
         hexline[hexcount] := hexdigs[ ORD(byte.ch[0]) DIV 16 ];
         hexcount := hexcount + 1;
         hexline[hexcount] := hexdigs[ ORD(byte.ch[0]) MOD 16 ];
         IF hexcount = maxhexline THEN BEGIN
            writeln(PSfile,hexline:hexcount);
            hexcount := 0;
         END;
      END;
   END
END
ELSE BEGIN
   (* raster info is encoded as run and repeat counts *)
   rowsleft := ht;
   hbit := wd;
   repeatcount := 0;
   rp := 1;
   bitpos := 8;
   byte.bits := [];
   WHILE rowsleft > 0 DO BEGIN
      count := PackedNum;
      WHILE count > 0 DO BEGIN
         IF (count < bitpos) AND (count < hbit) THEN BEGIN
            IF turnon THEN
               byte.bits := byte.bits + gpower[bitpos]
                                      - gpower[bitpos - count];
            hbit := hbit - count;
            bitpos := bitpos - count;
            count := 0;
         END
         ELSE IF (count >= hbit) AND (hbit <= bitpos) THEN BEGIN
            IF turnon THEN
               byte.bits := byte.bits + gpower[bitpos]
                                      - gpower[bitpos - hbit];
            (* SYSDEP: Pyramid Pascal stores bits 7..0 in the LEFT
               byte of a 4-byte BITSET word. *)
            row[rp] := byte.ch[0];
            (* end of current row, so send it repeatcount+1 times *)
            FOR i := 0 TO repeatcount DO
               FOR j := 1 TO bytesperrow DO BEGIN
                  hexcount := hexcount + 1;
                  hexline[hexcount] := hexdigs[ ORD(row[j]) DIV 16 ];
                  hexcount := hexcount + 1;
                  hexline[hexcount] := hexdigs[ ORD(row[j]) MOD 16 ];
                  IF hexcount = maxhexline THEN BEGIN
                     writeln(PSfile,hexline:hexcount);
                     hexcount := 0;
                  END;
               END;
            rowsleft := rowsleft - (repeatcount + 1);
            repeatcount := 0;
            rp := 1;
            byte.bits := [];
            bitpos := 8;
            count := count - hbit;
            hbit := wd;
         END
         ELSE BEGIN
            IF turnon THEN byte.bits := byte.bits + gpower[bitpos];
            row[rp] := byte.ch[0];
            rp := rp + 1;
            byte.bits := [];
            count := count - bitpos;
            hbit := hbit - bitpos;
            bitpos := 8;
         END;
      END;
      turnon := NOT turnon;
   END;
END;
IF hexcount > 0 THEN write(PSfile,hexline:hexcount);
writeln(PSfile, '>');
writeln(PSfile, bytesperrow * 8:1, ' ', ht:1, ' ', xo:1, ' ', yo:1, ' ',
                pwidth:1, '] ', code:1, ' dc');
END; (* WITH *)
END; (* LoadBitmap *)

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

FUNCTION FixToDVI (b0, b1, b2, b3 : INTEGER) : INTEGER;

(* Convert the given fix width (made up of 4 bytes) into DVI units
   using the method recommended in DVITYPE.
*)

VAR alpha, beta, temp, s : INTEGER;

BEGIN
WITH currfont^ DO BEGIN
   s := scaledsize;
   alpha := 16 * s;
   beta  := 16;
   WHILE s >= 8#40000000 DO BEGIN   (* 2^23 *)
      s := s DIV 2;
      beta := beta DIV 2;
   END;
   temp := (((((b3 * s) DIV 8#400) + (b2 * s)) DIV 8#400) + (b1 * s)) DIV beta;
   IF b0 > 0 THEN
      IF b0 = 255 THEN
         FixToDVI := temp - alpha
      ELSE BEGIN
         writeln; writeln('Bad TFM width! 1st byte = ', b0:1); exit(1);
      END
   ELSE
      FixToDVI := temp;
END;
END; (* FixToDVI *)

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

PROCEDURE PKFillPixelTable;

(* Fill the pixeltable for currfont^ using the font directory info
   in the currently open PK file.
*)

LABEL 888;

CONST
   pkid   =  89;
   pkpost = 245;
   pknoop = 246;
   pkpre  = 247;

VAR
   i, j, flagbyte, flagpos,
   chcode,                       (* assumed to be <= 255 *)
   packetlen, endofpacket,
   b0, b1, b2, b3 : INTEGER;     (* 4 bytes in TFM width *)

BEGIN
WITH currfont^ DO BEGIN
   PToffset := 0;                          (* move to first byte *)
   IF GetPTByte <> pkpre THEN BEGIN
      writeln; writeln('Bad pre command in ', fontspec:fontspeclen); exit(1);
   END;
   IF GetPTByte <> pkid THEN BEGIN
      writeln; writeln('Bad id byte in ', fontspec:fontspeclen); exit(1);
   END;
   j := GetPTByte;                         (* length of comment *)
   PToffset := PToffset + j + 16;          (* skip rest of preamble *)
   FOR i := 0 TO maxTeXchar DO
      WITH pixelptr^[i] DO BEGIN
         mapadr := 0;                      (* all chars absent initially *)
         loaded := FALSE;                  (* bitmap not yet downloaded *)
      END;
   WHILE TRUE DO BEGIN
      flagpos  := PToffset;                (* remember position of flagbyte *)
      flagbyte := GetPTByte;
      IF flagbyte < 240 THEN BEGIN         (* read character definition *)
         flagbyte := flagbyte MOD 8;       (* value of bottom 3 bits *)
         IF flagbyte < 4 THEN BEGIN        (* short char preamble *)
            packetlen := flagbyte * 256 + GetPTByte;
            chcode    := GetPTByte;
            endofpacket := packetlen + PToffset;
            WITH pixelptr^[chcode] DO BEGIN
               b1     := GetPTByte;
               b2     := GetPTByte;
               b3     := GetPTByte;
               dwidth := FixToDVI(0,b1,b2,b3);   (* b0 = 0 *)
               pwidth := GetPTByte;
               wd     := GetPTByte;
               ht     := GetPTByte;
               xo     := SignedPTByte;
               yo     := SignedPTByte;
            END;
         END
         ELSE IF flagbyte < 7 THEN BEGIN   (* extended short char preamble *)
            packetlen := (flagbyte - 4) * 65536 + GetTwoPTBytes;
            chcode    := GetPTByte;
            endofpacket := packetlen + PToffset;
            WITH pixelptr^[chcode] DO BEGIN
               b1     := GetPTByte;
               b2     := GetPTByte;
               b3     := GetPTByte;
               dwidth := FixToDVI(0,b1,b2,b3);   (* b0 = 0 *)
               pwidth := GetTwoPTBytes;
               wd     := GetTwoPTBytes;
               ht     := GetTwoPTBytes;
               xo     := SignedPTPair;
               yo     := SignedPTPair;
            END;
         END
         ELSE BEGIN                        (* long char preamble *)
            packetlen := SignedPTQuad;
            chcode    := SignedPTQuad;
            endofpacket := packetlen + PToffset;
            WITH pixelptr^[chcode] DO BEGIN
               b0     := GetPTByte;
               b1     := GetPTByte;
               b2     := GetPTByte;
               b3     := GetPTByte;
               dwidth := FixToDVI(b0,b1,b2,b3);
               pwidth := SignedPTQuad DIV 65536;   (* dx in pixels *)
               PToffset := PToffset + 4;           (* skip dy *)
               wd     := SignedPTQuad;
               ht     := SignedPTQuad;
               xo     := SignedPTQuad;
               yo     := SignedPTQuad;
            END;
         END;
         WITH pixelptr^[chcode] DO
            IF (wd = 0) OR (ht = 0) THEN
               mapadr := 0                 (* no bitmap *)
            ELSE
               mapadr := flagpos;          (* position of flagbyte *)
         PToffset := endofpacket;          (* skip raster info *)
      END
      ELSE
         CASE flagbyte OF
            240, 241, 242, 243 :
                       BEGIN
                       i := 0;
                       FOR j := 240 TO flagbyte DO i := 256 * i + GetPTByte;
                       PToffset := PToffset + i;   (* skip special parameter *)
                       END;
            244      : PToffset := PToffset + 4;   (* skip numspecial param *)
            pknoop   : ;                           (* do nothing *)
            pkpost   : goto 888;                   (* no more char defs *)
         OTHERWISE
            writeln; writeln('Bad flag byte in ', fontspec:fontspeclen);
            exit(1);
         END;
   END; (* of LOOP; flagbyte = pkpost *)
   888:
END;
END; (* PKFillPixelTable *)

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

PROCEDURE ReadTFMIntegers;

(* Read the first 6 16-bit integers in the TFM file.  See TFtoPL section 8. *)

BEGIN
PToffset := 0;   (* start reading at 1st byte in TFM file *)
lf := GetTwoPTBytes;
lh := GetTwoPTBytes;
bc := GetTwoPTBytes;
ec := GetTwoPTBytes;
nw := GetTwoPTBytes;
nh := GetTwoPTBytes;
END; (* ReadTFMIntegers *)

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

PROCEDURE ReadTFMCharInfo;

(* Read the TFMinfo array.  See TFtoPL section 11. *)

VAR c, i : INTEGER;

BEGIN
PToffset := 24 + (lh * 4);          (* offset of TFMinfo array *)
FOR c := bc TO ec DO
   WITH TFMinfo[c] DO BEGIN
      wdindex  := GetPTByte * 4;    (* offset from start of width array *)
      i        := GetPTByte;        (* 2nd byte contains htindex and dpindex *)
      htindex  := (i DIV 16) * 4;   (* offset from start of height array *)
      dpindex  := (i MOD 16) * 4;   (* offset from start of depth array *)
      PToffset := PToffset + 2;     (* skip itindex and remainder bytes *)
   END;
END; (* ReadTFMCharInfo *)

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

PROCEDURE ReadTFMCharMetrics;

(* Read the charmetrics array using the indices in TFMinfo. *)

VAR wdbase, htbase, dpbase, b, c : INTEGER;

BEGIN
wdbase := 24 + lh * 4 + (ec - bc + 1) * 4;   (* offset of width array *)
htbase := wdbase + nw * 4;                   (* offset of height array *)
dpbase := htbase + nh * 4;                   (* offset of depth array *)
FOR c := bc TO ec DO
   WITH TFMinfo[c] DO
   WITH charmetrics[c] DO BEGIN
      PToffset := wdbase + wdindex;
      FOR b := 0 TO 3 DO width[b] := GetPTByte;
      PToffset := htbase + htindex;
      FOR b := 0 TO 3 DO height[b] := GetPTByte;
      PToffset := dpbase + dpindex;
      FOR b := 0 TO 3 DO depth[b] := GetPTByte;
   END;
END; (* ReadTFMCharMetrics *)

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

PROCEDURE TFMFillPixelTable;

(* Fill the pixeltable for currfont^ (a PostScript font)
   using information in the currently open TFM file.
*)

VAR c, dheight, pheight, ddepth, pdepth : INTEGER;

BEGIN
ReadTFMIntegers;                         (* read lf..nh *)
ReadTFMCharInfo;                         (* fill TFMinfo array *)
ReadTFMCharMetrics;                      (* fill charmetrics array *)
WITH currfont^ DO BEGIN
   FOR c := 0 TO bc - 1 DO
      pixelptr^[c].mapadr := 0;          (* chars < bc don't exist *)
   FOR c := ec + 1 TO 255 DO
      pixelptr^[c].mapadr := 0;          (* chars > ec don't exist *)
   FOR c := bc TO ec DO
      WITH pixelptr^[c] DO
      WITH charmetrics[c] DO BEGIN
         dwidth  := FixToDVI(width[0],width[1],width[2],width[3]);
         dheight := FixToDVI(height[0],height[1],height[2],height[3]);
         ddepth  := FixToDVI(depth[0],depth[1],depth[2],depth[3]);
         (* convert DVI units to pixels *)
         pwidth  := PixelRound(dwidth);
         pheight := PixelRound(dheight);
         pdepth  := PixelRound(ddepth);
         (* Since we don't have access to bitmap info for a PostScript font
            we will have to use the TFM width/height/depth info to
            approximate wd, ht, xo, yo.
         *)
         wd := pwidth;
         wd := wd - (wd DIV 8);          (* better approximation *)
         ht := pheight + pdepth;
         xo := 0;
         yo := pheight - 1;
         IF (wd = 0) OR (ht = 0) THEN
            mapadr := 0                  (* char all-white or not in font *)
         ELSE
            mapadr := 1;                 (* anything but 0 *)
         loaded := FALSE;                (* no bitmap available *)
      END;
END;
END; (* TFMFillPixelTable *)

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

PROCEDURE PixelTableRoutine;

(* DVIReader has just allocated a new pixeltable for currfont^ and
   calls this routine from InterpretPage only ONCE per font
   (the first time the font is used).
   We get the pixeltable information from the font file given by fontspec.
   We also set fontid to a unique identifier of the form "fontname.fontsize".
   If fontspec does not exist then dummyfont is used and fontid is undefined.
   We don't output any PostScript for non-existent fonts.
*)

VAR i, fontsizelen, firstn, lastn : INTEGER;

BEGIN
(* Initialize currfont^.fontspec and return start and end of fontsize
   (unless psfont flag is set to TRUE).
   currfont^.fontexists may also become TRUE.
*)
BuildFontSpec(currfont,firstn,lastn);
WITH currfont^ DO BEGIN
   IF OpenFontFile(fontspec) THEN BEGIN
      (* only need fontid for a bitmapped font *)
      IF NOT psfont THEN BEGIN
         fontid := fontname;
         fontsizelen := lastn - firstn + 1;
         IF fontnamelen + fontsizelen < maxfontspec THEN BEGIN
            (* append ".fontsize" to fontid *)
            fontid[fontnamelen] := '.';
            FOR i := 1 TO fontsizelen DO
               fontid[fontnamelen + i] := fontspec[firstn + i - 1];
         END
         ELSE BEGIN
            (* in the unlikely event that there is no room to append ".fontsize"
               we simply leave fontid = fontname and hope it's unique *)
            writeln;
            writeln('Warning! fontname too long: ', fontname:fontnamelen);
         END;
         IF NOT conserveVM THEN NewBitmapFont(fontid);
      END;
   END
   ELSE IF OpenFontFile(dummyfont) THEN BEGIN
      (* fontid is left undefined; it will not be used *)
      warncount := warncount + 1;
      writeln;
      writeln('Couldn''t open font file: ', fontspec:fontspeclen);
      (* use dummy font info instead *)
   END
   ELSE BEGIN
      writeln;
      writeln('Couldn''t open dummy font: ', dummyfont:Len(dummyfont));
      exit(1);
   END;
   IF psfont AND fontexists THEN
      TFMFillPixelTable
   ELSE
      PKFillPixelTable;
   CloseFontFile;
END;
END; (* PixelTableRoutine *)

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

PROCEDURE InitFontReader;

(* This routine initializes some global variables. *)

VAR i : INTEGER;

BEGIN
hexdigs := '0123456789ABCDEF';         (* for LoadBitmap *)
gpower[0] := [];
FOR i := 1 TO 8 DO
   gpower[i] := gpower[i-1] + [i-1];   (* for LoadBitmap *)
psprefixlen := Len(psprefix);
fontdirlen  := Len(fontdir);
END; (* InitFontReader *)