summaryrefslogtreecommitdiff
path: root/dviware/ln03/thomas/pk.c
blob: b3115fd61dd96825ec615ad70ba3733ff9dfac41 (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
/* Copyright (C) 1987, Matt Thomas

Here starts the code for processing PK files.  It was designed to be able
to run on any byte addressable CPU, but primarily the VAX.  If you wonder 
why I did something the way I did, think of the machine code it would produce.
For instance, I AND instead MOD if I would be MODing by a power of two.  In 
other words, I make life for compiler optimizer.  I make one assumption.  This 
code will always be run on a machine with a large address space and an infinite
heap (PDP-11s are out of luck).

PK files are big-endian but the VAX [and the LN03] are little endian.  So
everything is backwards!  So we have reverse things as we go.  Keep this in
mind as you study the code below.  Also a copy of PKtoPX.WEB is very useful
to have nearby while studying this code. 

This code is divided into three parts, the first is the generic part.  This
is where I define by module global variables, macro, includes files, etc.
The second part is font hadnling code.  And the the third id the glyph
handling code.  Each part can be easily found in a listing by looking for
either GENERIC, FONTS, or GLYPHS in large block letters.

If you find any bugs in following code, please send me a mail message
telling me where I screwed up.  On the Easynet, use THEBAY::MTHOMAS.
On USENET, try ...!ptsfa!ista!thomas.  On the Internet, use 
ptsfa!ista!thomas@{sun.com,lll-crg.arpa,lll-lcc.arpa,ames.nasa.gov}  

Thanks,
Matt Thomas
PO BOX 121
Rheem Valley, CA 94570.
*/

/***************************************************************************
****************************************************************************


  GGGGGGGG  EEEEEEEEE  NN    NN  EEEEEEEE  RRRRRRRR    IIIIIIII    CCCCCCC
GG          EE         NNN   NN  EE        RR      RR     II     CC       CC
GG          EE         NNNN  NN  EE        RR      RR     II     CC
GG    GG    EEEEE      NN NN NN  EEEEE     RRRRRRRR       II     CC
GG      GG  EE         NN  NNNN  EE        RR    RR       II     CC
GG      GG  EE         NN   NNN  EE        RR     RR      II     CC      CC
  GGGGGG    EEEEEEEEE  NN    NN  EEEEEEEE  RR      RR  IIIIIIII    CCCCCC


***************************************************************************
**************************************************************************/
/*	I N C L U D E S		*/

#ifdef vms
#include stdio.h
#include errno.h
#include stat.h
#else
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#endif
#include "pk.h"

/*
/*  Errno gets defined in different ways on different machines.
/*  Under VMS and System V, it gets defined in errno.h but under
/*  BSD 4.x you have declare it yourself.  Also we use strchr
/*  instead of index (BSD version) so we conditionalize that here
/*  too.
*/
#ifdef  bsd4_2
# define strchr index
extern int errno;
#endif


/****************************************************
*****************************************************


FFFFFFFFF    OOOOOO    NN    NN  TTTTTTTT    SSSSSS
FF         OO      OO  NNN   NN     TT     SS      SS
FF         OO      OO  NNNN  NN     TT     SS
FFFFFF     OO      OO  NN NN NN     TT       SSSSSS
FF         OO      OO  NN  NNNN     TT             SS
FF         OO      OO  NN   NNN     TT     SS      SS
FF           OOOOOO    NN    NN     TT       SSSSSS


*****************************************************
****************************************************/


#ifdef ANSIC
extern	PKFont *	PKLoadFont( char fontname, int magnification, int pixelsize );
extern	void		PKTrimFont( PKFont *fontptr );
extern	void		PKUnloadFont( PKFont *fontptr );
static	float		PKAcutalFactor( int magnification );
static	char *		PKGetFontFileName( char *fontname, int magnification, int pixelsize );
static	PKFont *	PKReadFontPreamble( PKFont *fontptr );
#else
extern	PKFont *	PKLoadFont();
extern	void		PKTrimFont();
extern	void		PKUnloadFont();
static	float		PKAcutalFactor();
static	char *		PKGetFontFileName();
static	PKFont *	PKReadFontPreamble();
#endif

/*  This routine opens the PK file.  In addition for reasons of speed and
efficency, it is easier and faster to malloc enough memory to store the
entire PK file in memory than to read and seek as needed from the file. 
So in this routine, not only do we open the PK file but we also completely 
read it into the malloc'ed buffer.  We also read the preamble to verify
the magnification and to get the font characterstics. */

PKFont *
PKLoadFont( fontname, magnification, pixelsize )
char *fontname;
int magnification;
int pixelsize;
{
    PKFont  *fontptr;
    int i,j, pkf;
    char *filespec;
    struct stat stat_buf;

    PKerror[0] = '\0';

    filespec = PKGetFontFileName( fontname, magnification, pixelsize );
    pkf = open(filespec,0);
    if  (pkf == -1)  {
	(void) strcpy( PKerror, filespec );
	return(NULL);
    }

    j = sizeof(PKFont) + strlen(fontname) + 1;
    fontptr = (PKFont *) malloc( j );
    if  (fontptr == NULL) {
	sprintf( PKerror, "can't malloc %ld bytes for font structure", j );
	close(pkf);
	return(NULL);
    }

    fontptr->fontname = ((char *) fontptr) + sizeof(PKFont);
    strcpy( fontptr->fontname, fontname );

    fontptr->filespec = filespec;

    for ( i = 0; i <= PKMAXGLYPH; i++ ) {
	fontptr->packed_glyphs[i] = NULL;
	fontptr->unpacked_glyphs[i] = NULL;
    }

/* Seek to the end of the file to determine the size of the 
file, free the previously malloc'ed buffer, and then malloc 
enough heap to save it in memory.  After that is done, seek 
back to the beginning of the file, and read the contents
into the just malloc'ed buffer.  KLUDGE ALERT!!!  Since fstat
under VMS doesn't work across DECnet, we kludge around by just 
allocating a buffer of 100KB and hope it's enough.  */

    i = fstat( pkf, &stat_buf );
    if  (i < 0) {
#ifdef  vms
	if  (errno == ENXIO || errno == 0) {
	    register char *str = getenv("PKMAXFONTSIZE");
	    j = PKMAXFONTSIZE;
	    if  (str != NULL) {
		j = atol(str);
		if  (j < PKMAXFONTSIZE)
		    j = PKMAXFONTSIZE;
	    }
	    stat_buf.st_size = -1;
	    fontptr->fontsize = j;
	} else {
#endif
	    sprintf( PKerror, "fstat failed: errno = %d", errno );
	    close(pkf);
	    PKUnloadFont( fontptr );
	    return(NULL);
#ifdef	vms
	}
#endif
    } else {
	fontptr -> fontsize = stat_buf.st_size;
    }
    fontptr -> fontstream = (unsigned char *) malloc( fontptr->fontsize );
    if  (i < 0) {
	sprintf( PKerror, "fstat failed: errno = %d", errno );
	close(pkf);
	PKUnloadFont( fontptr );
	return(NULL);
    }
    fontptr -> fontsize = stat_buf.st_size;
    fontptr -> fontstream = (unsigned char *) malloc( fontptr->fontsize );
    if  (fontptr->fontstream == NULL) {
	sprintf( PKerror, "can't malloc %ld bytes for file buffer", fontptr->fontsize );
	close(pkf);
	PKUnloadFont( fontptr );
	return(NULL);
    }

/* read the file into the just allocated memory buffer */

    i = 0;
    do  {
	j = read(pkf, fontptr->fontstream+i, fontptr->fontsize-i);
	i += j;
    }   while  ( j > 0 && i < fontptr->fontsize );

    if  (j < 0) {
	strcpy(PKerror,"read error: errno = %d", errno);
	close(pkf);
	PKUnloadFont( fontptr );
	return(NULL);
    } else if (i < fontptr->fontsize && stat_buf.st_size != -1) {
	sprintf( PKerror,
		"error: premature EOF (%d of %d)", 
		i, fontptr->fontsize);
	close(pkf);
	PKUnloadFont( fontptr );
	return(NULL);
    }
    close(pkf);

    fontptr = PKReadFontPreamble( fontptr );
    return (fontptr);
}


extern	void
PKTrimFont( fontptr )
PKFont	*fontptr;
{
    PKerror[0] = '\0';

    if  (fontptr->fontstream != NULL)
	free( fontptr->fontstream );
    fontptr->fontstream = NULL;

    return;
}

/*  This routines frees all storage associated with a font. */

extern	void
PKUnloadFont( fontptr )
PKFont	*fontptr;
{
    int idx;

    PKerror[0] = '\0';

    for( idx = 0; idx <= PKMAXGLYPH; idx ++ )
	PKFreeGlyph( fontptr->unpacked_glyphs[idx] );

    if  (fontptr->filespec != NULL)
	free( fontptr->filespec );

    if  (fontptr->fontstream != NULL)
	free( fontptr->fontstream );

    return;
}


/* This routine is taken from dvi2ps and is used to get around rounding
errors in the integer form of the magnification. */

static	float
PKActualFactor(unmodsize)
int unmodsize;  /* actually factor * 1000 */
{
    float realsize;	/* the actual magnification factor */
 
    realsize = (float)unmodsize / 1000.0;
    /* a real hack to correct for rounding in some cases--rkf */
    if(unmodsize==1095) realsize = 1.095445;	/*stephalf*/
    else if(unmodsize==1315) realsize=1.314534;	/*stepihalf*/
    else if(unmodsize==2074) realsize=2.0736;	/*stepiv*/
    else if(unmodsize==2488) realsize=2.48832;  /*stepv*/
    else if(unmodsize==2986) realsize=2.985984;	/*stepiv*/
    /* the remaining magnification steps are represented with sufficient
	   accuracy already */
    return(realsize);
}

/* This routine constructs the file name from supplied fontname and
magnification.  If the magnification is non-positive, then the font name
is considered to be the filename.  When not running under VMS, if colons
are present in the TEXPKDIR variable, then each directory is searched for
the PK file until eith no more directories or a file is found.  */

static	char	*
PKGetFontFileName( fontname, magnification, pixelsize )
char	*fontname;
int	magnification;
int	pixelsize;
{
    char *pathlist, *pp, *pkdir;
    char *filespec = (char *) malloc( strlen(fontname) + 8 );
    char *fullspec = (char *) malloc( PKFILESPECLENGTH + 1 );

    strcpy(filespec, fontname);
    if  (magnification > 0) {
	int fext = (float) pixelsize * 
		    (float) PKActualFactor(magnification) + 0.5;
	sprintf( &filespec[strlen(filespec)], ".%dpk\0", fext);
    }

#ifdef vms
    strcpy( PKerror, filespec );
    pathlist = "tex$pkdir:";
    sprintf( fullspec, "%s%s", pathlist, filespec );
#else
    pkdir = (char *) getenv("TEXPKDIR");
    if  (pkdir == NULL)
	pkdir = "/usr/lib/tex/pkdir";
    pathlist = (char *) malloc( strlen(pkdir) + 1 );
    strcpy( pathlist, pkdir );
    pkdir = pathlist;
    while (1) {
	pp = (char *) strchr(pathlist, ':');
	if (pp != NULL)
	    *pp = '\0';
	sprintf( fullspec, "%s/%s", pathlist, filespec );
	if (0 <= access(fullspec, 4)) {
	    strcpy( PKerror, filespec );
	    break;
	}
	if (pp != NULL)
	    pathlist = pp + 1;
	strcpy( PKerror, fullspec );
	if (pp == NULL)
	    break;
    }
    free( pkdir );
#endif
    free( filespec );
    return(fullspec);
}


/* This routine reads the preamble of the PK file and verifies it's 
consistency and reads the font's characteristics into the PKFont
structure pointed by fontptr.  If an error is found Pkerror will contain
an error message, the font is unloaded, and a NULL will be returned. */

static	PKFont *
PKReadFontPreamble( fontptr )
register PKFont	*fontptr;
{

    fontptr->fontidx = fontptr->fontstream;
    if  (Get_8Bit_Unsigned(fontptr->fontidx) != PK_PRE) {
	sprintf(PKerror, "error: bad PK file (no preamble)");
	PKUnloadFont( fontptr );
	return(NULL);
    }
    if  (Get_8Bit_Unsigned(fontptr->fontidx) != PK_ID) {
	sprintf(PKerror, "bad PK file (invalid id %d)",
		fontptr->fontstream[1] );
	PKUnloadFont( fontptr );
	return( NULL );
    }

/*  Calculate the true magnification. */

    /* skip the comment */
    fontptr->fontidx += Get_8Bit_Unsigned(fontptr->fontidx);

    fontptr->design_size	= Get_32Bit_Unsigned(fontptr->fontidx);
    fontptr->checksum		= Get_32Bit_Unsigned(fontptr->fontidx);
    fontptr->v_pixels_per_point = Get_32Bit_Unsigned(fontptr->fontidx);
    fontptr->h_pixels_per_point = Get_32Bit_Unsigned(fontptr->fontidx);

    fontptr->magnification = 5.0 * (float) fontptr->h_pixels_per_point
		* 72.27 / 65536.0 + 0.5;

    return(fontptr);
}

/*********************************************************************
**********************************************************************



  GGGGGGGG   LL        YY      YY  PPPPPPPP    HH      HH    SSSSSSS
GG           LL         YY    YY   PP      PP  HH      HH  SS       SS
GG           LL           YYYY     PP      PP  HH      HH  SS
GG   GGG     LL            YY      PPPPPPPP    HHHHHHHHHH    SSSSSS
GG      GG   LL            YY      PP          HH      HH          SS
GG      GG   LL            YY      PP          HH      HH  SS      SS
  GGGGGG     LLLLLLLLLL    YY      PP          HH      HH    SSSSSS


*********************************************************************
********************************************************************/

/*
/*	Get a specific glyph from the PK file
*/
extern	PKGlyph *	PKGetGlyph();

/*
/*	Get a specific glyph from the PK file, analyze it's preamble,
/*	but DON'T unpack it.
*/
extern	PKGlyph *	PKGetGlyphInfo();

/*
/*	get the next glyph from the PK file
*/
extern	PKGlyph *	PKGetNextGlyph();

/*
/*	Free storage associated with a glyph.
*/
extern	void		PKFreeGlyph();

/*
/*	Find the glyph in the PK file and return a pointer to it
*/
static	unsigned char *	PKScanForGlyph();

/*
/*	Skip commands in the PK file stream.
*/
static	unsigned char *	PKSkipSpecials();

/*
/*	decodes a glyph requested by 1 or 2
*/
static	PKGlyph *	PKDecodeGlyph();

/*
/*	Read the character preamble and returna a pointer
/*	to a PKGlyph structure with the requested information.
*/
static	PKGlyph *	PKReadPreamble();

/*
/*	Unpack run-length encoded rasters
*/
static	void		PKUnpackRasters();

/*
/*	Copy the unencoded raster format
*/
static	void		PKCopyRasters();


/* This routine retrives a specific glyph from the supplied font. */

PKGlyph	*
PKGetGlyph( fontptr, glyph_id )
PKFont	*fontptr;
int	glyph_id;
{
    PKGlyph  *glyphptr;

    PKerror[0] = '\0';

    if  (glyph_id > PKMAXGLYPH || glyph_id < 0) {
	sprintf( PKerror, 
		"invalid glyph (%d): must be in the range from 0 to %ld",
		glyph_id, PKMAXGLYPH );
	return(NULL);
    }

    if  (fontptr->unpacked_glyphs[glyph_id] == NULL)
	glyphptr = PKReadPreamble( PKScanForGlyph( fontptr, glyph_id ) );
    else
	glyphptr = fontptr->unpacked_glyphs[glyph_id];

    if  (glyphptr != NULL) {
	glyphptr->fontptr = fontptr;
	glyphptr = PKDecodeGlyph( glyphptr );
	(fontptr->unpacked_glyphs)[glyph_id] = glyphptr;
    }

    if  (glyphptr == NULL) {
	sprintf( PKerror, "glyph %d not in file", glyph_id );
    }

   return(glyphptr);
}


/* This routine retrives a specific glyph from the supplied font. */

PKGlyph	*
PKGetGlyphInfo( fontptr, glyph_id )
PKFont	*fontptr;
int	glyph_id;
{
    PKGlyph  *glyphptr;

    PKerror[0] = '\0';

    if  (glyph_id > PKMAXGLYPH || glyph_id < 0) {
	sprintf( PKerror, 
		"invalid glyph (%d): must be in the range from 0 to %ld",
		glyph_id, PKMAXGLYPH );
	return(NULL);
    }

    if  (fontptr->unpacked_glyphs[glyph_id] == NULL)
	glyphptr = PKReadPreamble( PKScanForGlyph( fontptr, glyph_id ) );
    else
	glyphptr = fontptr->unpacked_glyphs[glyph_id];

    if  (glyphptr != NULL) {
	glyphptr->fontptr = fontptr;
	(fontptr->unpacked_glyphs)[glyph_id] = glyphptr;
    }

    if  (glyphptr == NULL) {
	sprintf( PKerror, "glyph %d not in file", glyph_id );
    }

    return(glyphptr);
}


PKGlyph	*
PKGetNextGlyph( fontptr )
PKFont	*fontptr;
{
    PKGlyph *glyphptr;

    PKerror[0] = '\0';

    if (fontptr == NULL) {
	sprintf( PKerror, "font not defined" );
	return(NULL);
    }

    glyphptr = PKReadPreamble( PKScanForGlyph( fontptr, -1 ) );

    if  (glyphptr != NULL) {
	glyphptr->fontptr = fontptr;
	glyphptr = PKDecodeGlyph( glyphptr );
	fontptr->unpacked_glyphs[glyphptr->glyph_id] = glyphptr;
    }

    return(glyphptr);
}


void
PKFreeGlyph( glyphptr )
PKGlyph *glyphptr;
{
    if  (glyphptr == NULL)
	return;
    glyphptr->fontptr->unpacked_glyphs[glyphptr->glyph_id] = NULL;

    if  (glyphptr->rasters != NULL)
	free(glyphptr->rasters);

    free(glyphptr);
}

/* Since a PK file does not a directory as does a PXL file we must scan
the PK file to find a glyph.  Also since a PK file may not be sorted in
ascending order, we may have to scan the entire file.  To save time on
scanning for later glyphs, we remeber the locations of the glyphs we
enounter.  

We scan the PK file without unpacking because each character preamble
contains the length of packed glyph.  Hence we need only read enough
to obtain the packet_length and the glyph_id.  

[[This would be a good time to get PXtoPK.WEB.]]

There are three types of character preambles in a PK file: short, extended
short, and long.  The first byte of every preamble in called the flag_byte.
It contains three fields, only one of which is used in this routine.  It is
contained in bits 0-2 (the lower three bits) and indicates the type of the
preamble.  Values 0-3 indicate a short preamble, 4-6 a extended short, and 7
a long.

All the preambles (at least the part we char about here) have three parts:
the flag_byte [[flag]], the packet_length [[pl]], and the glyph_id [[cc]].

In a short preamble, both the packet_length and the glyph_id are unsigned
bytes.  Also the bottom two bits of the flag_byte are multipled by 256 and
the result is added to get the true packet length.

In an extended short preamble, the packet_length is a two byte unsigned word
while the glyph_id is an unsigned char.  The bottom two bits of the flag_byte
should be multiplied by 65536 and added to packet_length.

In a long preamble, both the packet_length and the glyph_id are four byte
integers.

That's all for now.
*/

static unsigned char *
PKScanForGlyph( fontptr, target )
register PKFont *fontptr;
int target;
{
    unsigned char flag_byte, *glyphptr = NULL;
    register unsigned char *streamptr;
    int packet_length, glyph_id;

    /*
    /*  If we have done a PKTrimFont, don't scan.
    */
    if  (fontptr->fontstream == NULL)
	return(NULL);

    /*
    /*  See if we have previously scanned it.  If so,
    /*  return a pointer to it.  Othwise, search for it.
    */
    if  (target != -1) {
	glyphptr = fontptr->packed_glyphs[ target ];
	if  (glyphptr != NULL) {
	    return(glyphptr);
	}
    }

    streamptr = fontptr->fontidx;
    do  {
	flag_byte = *streamptr;
	if (flag_byte >= 240) {
	    if  (flag_byte == PK_POST) {
		sprintf( PKerror, "no more glyphs" );
		return(NULL);
	    }
	    streamptr = PKSkipSpecials( flag_byte, ++streamptr );
	    continue;
	}

/* Decode the character preambles to obtain packet lengths and the id of the
character. */

	glyphptr = streamptr++;
	flag_byte &= 0x07;
	if  (flag_byte < 4) {
	    packet_length = Get_8Bit_Unsigned( streamptr );
	    if  (flag_byte > 0)
		packet_length += flag_byte * 256;
	    glyph_id = Get_8Bit_Unsigned( streamptr );
	} else if (flag_byte < 7) {
	    packet_length = Get_16Bit_Unsigned(streamptr);
	    if  ((flag_byte -= 4) > 0)
		packet_length += flag_byte * 65536;
	    glyph_id = Get_8Bit_Unsigned( streamptr );
	} else {
	    packet_length = Get_32Bit_Unsigned(streamptr);
	    glyph_id = Get_32Bit_Unsigned(streamptr);
	}

/* Save the glyph's location for later retrieval.  Hopefully this will save
some CPU cycles.  Also note that glyphs don't have to be in ascending order
in a PK file.  If a PK file happened to ordered such the most common
characters are at the beginning, this could save a lot of time. */

	if  (fontptr->packed_glyphs[glyph_id] == NULL)  {
	    fontptr->packed_glyphs[glyph_id] = glyphptr ;
	} else {
	    sprintf( PKerror,
		"warning: duplicate glyph (%d) detected, ",
		glyph_id);
	}

/* [[Since we don't expand/decipher a packed glyph immediately, a corrupt PK
file would give us major confusion.  (The packet lengths would be the
killers) So we just assume the PK files are error-free.]] */

	streamptr += packet_length;

/* We have found what we are looking for, so exit the loop and decipjer it.
Otherwise keep on looking.  */

    } while ((glyph_id != target) && (target != -1));

    fontptr->fontidx = streamptr;
    if  (target == -1 || target == glyph_id) {
	return(glyphptr);
    } else {
	return(NULL);
    }
}


/* This routine skip commands that may be present in a PK file.  And in
reality we treat them all as NOPs.  See the PKtoPX.WEB for what they are
really used for.  */

static unsigned char *
PKSkipSpecials( flag_byte, streamptr )
unsigned char flag_byte, *streamptr;
{
    int i;
    switch (flag_byte) {
	case PK_XXX4: i += *streamptr++; i <<= 8;
	case PK_XXX3: i += *streamptr++; i <<= 8;
	case PK_XXX2: i += *streamptr++; i <<= 8;
	case PK_XXX1: i += *streamptr++;
	    streamptr += i;
	    break;
	case PK_YYY: streamptr += 4;
	    break;
	case PK_NO_OP:
	    break;
	default:
	    sprintf( PKerror, 
		"warning: detected illegal command %d",
		flag_byte );
    }
    return(streamptr);
}


/* This routine decodes a PK glyph and then return a pointer to a
PKglyph structure (which all the information about the glyph).  Normally
this routine is called by either PKGetGlyph or PKGetNextGlyph.  */

static PKGlyph *
PKDecodeGlyph( glyphptr )
PKGlyph *glyphptr;
{
    int bytes_per_row, raster_size, idx;

    if (glyphptr == NULL)
	return(NULL);

    if (glyphptr->rasters != NULL)
	return(glyphptr);


/* Decode the character preample, in either short, extended short, or long
format.  Now that the preamble is decoded, we can expand the packed rasters
(only if they would take up at least one byte). */

    bytes_per_row = (glyphptr->width + 7) / 8;
    raster_size = bytes_per_row * glyphptr->height + 1;
    glyphptr->rasters = (unsigned char *) malloc( raster_size );

    for (idx = 0; idx < raster_size; idx++)
	glyphptr->rasters[idx] = 0;

    if (glyphptr->height != 0 && glyphptr->width != 0) {
	if (glyphptr->dyn_f < 14) {
	    PKUnpackRasters( glyphptr );
	} else {
	    PKCopyRasters( glyphptr );
	}
    }

    return( glyphptr );
}


/* This routine reads the preamble for a character glyph in a PK file.
Doing it by brute force in by faar the easiet way to do it, so that's how we
do it.  The LET macro does away with a lot of drugde work.

[[Get your copy of PKtoPX.WEB again.]]

Back to preambles.  (see scan_for_glyph) preambles have more fields than
just the packet_length and the glyph_id.  In addition, there are:

	dyn_f:		See unpack_rasters
	black:		indicates initial run is black or white
	tfm_width:	width of character in .FIXes (I think)
	width:		width in pixels of minimum bound box for glyph
	height:		height ....
	hoffset:	horizontial offset to reference point (LLHC)
	voffset:	vertical ...
	hescapement:	horizonal escapement in 2^16 pixels
	vescapement:	vertical ...

There are others but we don't use them.  dyn_f is from bits 4-7 of the
flag_byte.  black is bit 3 of the flag_byte (useful only if dyn_f < 14).

All values are bytes in the short preamble except for tfm_width which is a 3
byte integer.  In the extended short from, all values are 2 byte words
except for tfm_width which, again, a 3 byte inetger.  In the long preamble,
all fields are 4 byte integers.  All fields are unsigned except for hoffset
and voffset which are always signed.

*/

static PKGlyph *
PKReadPreamble( streamptr )
register unsigned char *streamptr;
{
    unsigned flag_byte, dyn_f, color, packet_length, glyph_id;
    unsigned tfm_width, height, width, hescapement, vescapement;
    int hoffset, voffset;

    flag_byte		= Get_8Bit_Unsigned(streamptr);
    dyn_f		= (flag_byte >> 4);
    color		= ((flag_byte & 0x08) != 0);
    flag_byte		&= 0x07;

    if  (flag_byte < 4) {
	packet_length	= Get_8Bit_Unsigned(streamptr);
	glyph_id	= Get_8Bit_Unsigned(streamptr);
	tfm_width	= Get_24Bit_Unsigned(streamptr);
	hescapement	= Get_8Bit_Unsigned(streamptr) * 65536;
	vescapement	= 0;
	width		= Get_8Bit_Unsigned(streamptr);
	height		= Get_8Bit_Unsigned(streamptr);
	hoffset		= Get_8Bit_Signed(streamptr);
	voffset		= Get_8Bit_Signed(streamptr);
    } else if (flag_byte < 7) {
	packet_length	= Get_16Bit_Unsigned(streamptr);
	glyph_id	= Get_8Bit_Unsigned(streamptr);
	tfm_width	= Get_24Bit_Unsigned(streamptr);
	hescapement	= Get_16Bit_Unsigned(streamptr) * 65536;
	vescapement	= 0;
	width		= Get_16Bit_Unsigned(streamptr);
	height		= Get_16Bit_Unsigned(streamptr);
	hoffset		= Get_16Bit_Signed(streamptr);
	voffset		= Get_16Bit_Signed(streamptr);
    } else {
	packet_length	= Get_32Bit_Unsigned(streamptr);
	glyph_id	= Get_32Bit_Unsigned(streamptr);
	tfm_width	= Get_32Bit_Unsigned(streamptr);
	hescapement	= Get_32Bit_Unsigned(streamptr);
	vescapement	= Get_32Bit_Unsigned(streamptr);
	width		= Get_32Bit_Unsigned(streamptr);
	height		= Get_32Bit_Unsigned(streamptr);
	hoffset		= Get_32Bit_Signed(streamptr);
	voffset		= Get_32Bit_Signed(streamptr);
    }

    {	register PKGlyph *glyphptr;

	glyphptr = (PKGlyph *) malloc( sizeof(PKGlyph) );
	if  (glyphptr == NULL) {
	    sprintf( PKerror, "can't malloc %ld bytes for a PKGlyph", 
			sizeof(PKGlyph) );
	    return(NULL);
	}
	glyphptr->glyph_id = glyph_id;
	glyphptr->rasters = NULL;
	glyphptr->prasters = streamptr;
	glyphptr->tfm_width = tfm_width;
	glyphptr->width = width;
	glyphptr->height = height;
	glyphptr->h_offset = hoffset;
	glyphptr->v_offset = voffset;
	glyphptr->h_escapement = hescapement;
	glyphptr->v_escapement = vescapement;
	glyphptr->dyn_f = dyn_f;
	glyphptr->color = color;

	return(glyphptr);
    }
}


/* This routine decodes the packed rasters pointed to by glyphptr->prasters
and places the unpacked rasters in the buffer pointed to by
glyphptr->rasters.  Now if it were only that simple...

[[Got PKtoPX.WEB in hand?]]

This routine uses a companion functon, PKGetRunCount, to obtain the run
counts.

This routine is really just two nested loops.  The inner loop generates a
raster.  The outer loop copies it to the LN03 buffer.  The outer loop is the
simpler of the two, so I'll describe it first.

The outer loop has three parts.  The first is to clear the array pointed to
by row_ptr.  This is used to hold generated raster.  Second is to actually
generate the raster.  Lastly, it copies the generated raster to the LN03
buffer once, and then N more times (as indicated by the repeat_count).
The loop terminates when all rows have been processed.

The inner loop generates the raster and places it into the byte array
pointed to by row_ptr.  In each through the loop (until it terminates), we
can process a certain number of bits (c2).  The number is constrained by the
remaining length of the run count (count), the number of bits left to add to
finish the raster (width-col), and if the color is "black" the number of
bits remaining in the byte.  

Since the raster was initially cleared, we can skip over all "white" bits in
row as long as we account for them.  Hence, we can process multiple bytes at
a time with no problem.  

If the current color is black, then we are limited to what we can do to a
byte.  But since we do bit operations, we may be pointing to somewhere in
the middle of byte.  So we can, at most, process eight bits at time and
usually much less.  The current bit posiition in the current byte is
contained in bottom three bits of the column/raster counter, col.  This is
know as the bit wieght, bw.  A bit weight of 0 indicates that we are
currently byte-aligned.  So if the color is black, we can process up to
8-bw bits at time, at the resulting number of bits would be set starting at
bit bw.  To generate the bitmask, we simply OR BItMask[c2][bw] with the
current byte.

It may be complicated, but it's fast!

This routine contains a section of code that is equivalent to pk_packed_num in
PKtoPX.WEB.  The only real change from that function is that getnyb is now a C
macro.  One other change is that we don't get/store our results from/in global
variables, intead they are arguments to the function. 

To describe what this functions does is easy.  It returns the length of the
next stream of bits.  To describe how it does is not.  For that, i refer you
to PKtoPX.WEB and allow you to compare the code.

*/

#ifdef vax
struct	nybble_struct	{
	unsigned low_nyb : 4;
	unsigned high_nyb : 4;
	};

#define getnyb(ptr) ((glyphptr->nybflag) ? \
		(glyphptr->nybflag=0, \
		    (int) (((struct nybble_struct *) (ptr)++)->low_nyb)) : \
		(glyphptr->nybflag=1, \
		    (int) (((struct nybble_struct *) (ptr))->high_nyb))  \
		)
#else
#define getnyb(ptr) ((glyphptr->nybflag) ? \
		(glyphptr->nybflag=0, (ptr)++, (ptr)[-1] & 0x0f) : \
		(glyphptr->nybflag=1, *(ptr) >> 4) )
#endif
static void
PKUnpackRasters( glyphptr )
register PKGlyph *glyphptr;
{
    int height = glyphptr->height, width=glyphptr->width;
    int color = glyphptr->color;    
    unsigned char *outptr = glyphptr->rasters;
    unsigned char *inptr = glyphptr->prasters;

    int bytes_per_row, row, repeat_count, count, dyn_f;
    unsigned char *row_ptr, tmp_row[128];
#ifdef PKDEBUG
    printf("unpacking "); fflush(stdout);
#endif
    bytes_per_row = (width + 7) / 8;
    if  (bytes_per_row > sizeof(tmp_row)) {
	row_ptr = (unsigned char *) malloc( bytes_per_row );
	if  (row_ptr == NULL) {
	    sprintf( PKerror, "can't malloc %ld byte for raster buffer", 
			bytes_per_row );
	    return;
	}
    } else {
	row_ptr = tmp_row;
    }
    color ^= 1;	/* corrected on first run count */
    glyphptr->nybflag = 0;	/* start off right */
    dyn_f = glyphptr->dyn_f;	/* store it locally */

    for ( row=0, count=0; row < height; row += 1 + repeat_count) {
	register int col, idx;

	repeat_count = 0;
	for ( col = 0; col < bytes_per_row; col++ )
	    row_ptr[col] = 0;

	for ( col=0; col < width; ) { 
	    register int c2;
	    if (count == 0) {
		register int nyb = getnyb(inptr);
		if (nyb == 0) {
		    register  int j;
		    do  {
			j = getnyb(inptr);
			nyb++;
		    }   while (j == 0);
		    for ( ; nyb > 0; nyb-- )
			j = j*16 + getnyb(inptr);
		    count = j - 15 + (13 - dyn_f)*16 + dyn_f;
		} else if (nyb <= dyn_f) {
		    count = nyb;
		} else if (nyb < 14) {
		    count = (nyb - dyn_f - 1)*16 + getnyb(inptr) + dyn_f + 1;
		} else {
		    if  (nyb == 14)
			repeat_count = -1;  /* note that we need a repeat */
		    else
			repeat_count = 1;   /* repeat count is 1 */
		    continue;		/* cycle thru and the get the count */
		}
		if  (repeat_count == -1)  { /* need a repeat count? */
		    repeat_count = count;   /*     yes, save it */
		    count = 0;		    /*     zero the run count */
		    continue;		    /*     and get the run count */
		}
		color ^= 1;		/* toggle color */
	    }
	    c2 = width - col;
	    if  (count < c2)	c2 = count;
	    if  (color) {
		register unsigned bw = col & 7;
		if (8-bw < c2) c2 = 8-bw;
		row_ptr[ col/8 ] |= BitMask( c2, bw ); /* mask in the btis */
	    }
	    col += c2;			/* increment column count */ 
	    count -= c2;		/* decrement run count */
	}

	/*
	/*  Copy the completed raster to the output area. (N times)
	*/
	for (idx = repeat_count; idx >= 0; idx--) {
	    for ( col=0; col < bytes_per_row; col++ )
		*outptr++ = CopyByte(row_ptr[col]);
	}
     }

    if (count) {		/* consistency check */
	sprintf( PKerror, "%d extra bits after unpacking", count );
    }
    if  (bytes_per_row > sizeof(tmp_row))
	free(row_ptr);		/* free malloc'ed storage */
}



/* This function reads an unpacked PK raster and stores it into the LN03
font while byte/bit-reversing along the way.  It is almost identical to
copy_raster_by_bits in PKtoPX.WEB except some optimizarions have been added.

First, if the width happens to be a multiple of a 8 then we copy the row by
bytes instead by bit.  We use an array to unsigned char (rev_byte) to
reverse bits in the byte.  Second, we integrated the routine get_bt into
copy_pk_rasters.  This saves one function call for every bit.  On a VAX,
that is important.

Note that the inner loop is degenerative case of the inner loop of
unpack_raster which the count as always 1.  Also, instead of generating our
bitmasks by shifting, we use the BitMask array instead.

Lastly we do everything on a byte operand, not a four-byte integer.  This
maskes this code be extremely more transportable to other machines.  */

static void
PKCopyRasters( glyphptr )
PKGlyph	*glyphptr;
{
    register int row, ibw, idx = 0;
    int height = glyphptr->height, width = glyphptr->width;
    int bytes_per_row = (width + 7) / 8;
    register unsigned char *outptr = glyphptr->rasters;
    register unsigned char *inptr = glyphptr->prasters;

#ifdef PKDEBUG
    printf("copying "); fflush(stdout);
#endif
    if  ((width & 7) == 0) {	/* optimize */
#ifdef PKDEBUG
	printf( "by byte, " ); fflush(stdout);
#endif
	for ( row=bytes_per_row*height ; row > 0; row-- )
	    outptr[idx++] = ReverseByte(*inptr++);
    } else {
#ifdef PKDEBUG
	printf( "by bit, " ); fflush(stdout);
#endif
	for ( row=height, ibw=7; row > 0; row-- ) {
	    register int col, obw;
	    register unsigned char outbyte = 0;
	    for ( col=width,obw=0; col > 0; col-- ) {

		if  ((BitMask( 1, ibw ) & *inptr) != 0)
		    outbyte |= BitMask( 1, obw );

		if ((obw += 1) > 7) {
		    obw = 0;
		    outptr[idx++] = CopyByte(outbyte);
		    outbyte = 0;
		}
		if ((ibw -= 1) < 0) {
		    ibw = 7;
		    ++inptr;
		}
	    }
	    if (obw > 0) {
		obw = 0;
		outptr[idx++] = CopyByte(outbyte);
	    }
	}
    }
    if  (idx != (row = height * bytes_per_row))
	sprintf( "copied wrong number [%ld] of bytes, should be %ld",idx,row);
    return;
}