summaryrefslogtreecommitdiff
path: root/pcl/pl/pjparse.c
blob: add19c1e86fe936534010d77f5663d9f4a70bad9 (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
/* Copyright (C) 2001-2012 Artifex Software, Inc.
   All Rights Reserved.

   This software is provided AS-IS with no warranty, either express or
   implied.

   This software is distributed under license and may not be copied,
   modified or distributed except as expressly authorized under the terms
   of the license contained in the file LICENSE in this distribution.

   Refer to licensing information at http://www.artifex.com or contact
   Artifex Software, Inc.,  7 Mt. Lassen Drive - Suite A-134, San Rafael,
   CA  94903, U.S.A., +1(415)492-9861, for further information.
*/


/* pjparse.c */
/* PJL parser */
#include "stat_.h"
#include "memory_.h"
#include "stdio_.h"
#include "string_.h"
#include "scommon.h"
#include "gdebug.h"
#include "gp.h"
#include "gxiodev.h"
#include "pjparse.h"
#include "plfont.h"
#include "plver.h"              /* PJL_VOLUME_0 PJL_VOLUME_1 */
#include "ctype_.h"             /* for toupper() */
#include <stdlib.h>             /* for atoi() */

/* ------ pjl state definitions ------ */

#define PJL_STRING_LENGTH (256)
#define PJL_PATH_NAME_LENGTH (256)
#define MAXPATHLEN 1024

/* definitions for fontsource and font number table entries */
typedef struct pjl_fontsource
{
    char designator[2];
    char pathname[PJL_PATH_NAME_LENGTH + 1];
    char fontnumber[PJL_STRING_LENGTH + 1];
} pjl_fontsource_t;

/* definitions for variable names and values */
typedef struct pjl_envir_var_s
{
    char var[PJL_STRING_LENGTH + 1];
    char value[PJL_STRING_LENGTH + 1];
} pjl_envir_var_t;

/* the pjl current environment and the default user environment.  Note
   the default environment should be stored in NVRAM on embedded print
   systems. */
typedef struct pjl_parser_state_s
{
    char line[81];              /* buffered command line */
    int bytes_to_write;         /* data processing by fsdownload */
    int bytes_to_read;          /* data processed by fsupload */
    FILE *fp;                   /* fsdownload or fsupload file */
    int pos;                    /* current position in line */
    pjl_envir_var_t *defaults;  /* the default environment (i.e. set default) */
    pjl_envir_var_t *envir;     /* the pjl environment */
    /* these are seperated out from the default and environmnet for no good reason */
    pjl_fontsource_t *font_defaults;
    pjl_fontsource_t *font_envir;
    char *environment_font_path;        /* if there is an operating sytem env
                                           var it is used instead of the
                                           default pjl fontsource */
    gs_memory_t *mem;
} pjl_parser_state_t;

/* provide factory defaults for pjl commands.  Note these are not pjl
   defaults but initial values set in the printer when shipped.  In an
   embedded system these would be defined in ROM */
static const pjl_envir_var_t pjl_factory_defaults[] = {
    {"formlines", "60"},
    {"formlines_set", "off"},
    {"widea4", "no"},
    {"edgetoedge", "no"},
    {"fontsource", "I"},
    {"fontnumber", "0"},
    {"pitch", "10.00"},
    {"ptsize", "12.00"},
    /* NB pc8 is used on 6mp, clj4550, clj4600
       roman8 is used on most other HP devices */
    {"symset", "pc8"},
    {"copies", "1"},
    {"paper", "letter"},
    {"orientation", "portrait"},
    {"duplex", "off"},
    {"binding", "longedge"},
    {"manualfeed", "off"},
    {"fontsource", "I"},
    {"fontnumber", "0"},
    {"personality", "pcl5c"},
    {"language", "auto"},
    {"disklock", "off"},
    {"plotsizeoverride", "off"},        /* override hpgl/2 PS command args */
    {"plotsize1", "0"},         /* 1st arg to PS - plotter units */
    {"plotsize2", "0"},         /* 2nd arg to PS - plotter units */
    {"paperwidth", ""},
    {"paperlength", ""},
    {"resolution", "0"},
    /*    {"personality", "rtl"}, */
    {"", ""}
};

/* NB this must be kept synchronized with the table above and we
   should probably have index definitions for each variable */
#define FDEF_PAPER_INDX 8

/* FONTS I (Internal Fonts) C, C1, C2 (Cartridge Fonts) S (Permanent
   Soft Fonts) M1, M2, M3, M4 (fonts stored in one of the printer's
   ROM SIMM slots).  Simulate cartridge, permanent soft fonts, and
   printer ROM SIMMS with sub directories.  See table below.  Also
   resources can be set up as lists of resources which is useful for
   host based systems.  Entries are seperated with a semi-colon.  Note
   there is some unnecessary overlap in the factory default and font
   source table. */
static const pjl_fontsource_t pjl_fontsource_table[] = {
    {"I",
     "%rom%ttfonts/;fonts/;urwfonts/;/windows/fonts/;/win95/fonts/;/winnt/fonts/"},
    {"C", "CART0/", ""},
    {"C1", "CART1/", ""},
    {"C2", "CART2/", ""},
    {"S", "MEM0/", ""},
    {"M1", "MEM1/", ""},
    {"M2", "MEM2/", ""},
    {"M3", "MEM3/", ""},
    {"M4", "MEM4/", ""},
    {"", "", ""}
};

/* pjl tokens parsed */
typedef enum
{
    DONE,
    SET,
    DEFAULT,
    EQUAL,
    VARIABLE,
    SETTING,
    UNIDENTIFIED,               /* NB not used */
    LPARM,                      /* NB not used */
    PREFIX,                     /* @PJL */
    INITIALIZE,
    RESET,
    INQUIRE,
    DINQUIRE,
    ENTER,
    LANGUAGE,
    ENTRY,
    COUNT,
    OFFSET,
    FSDOWNLOAD,
    FSAPPEND,
    FSDELETE,
    FSDIRLIST,
    FSINIT,
    FSMKDIR,
    FSQUERY,
    FSUPLOAD,
    FORMATBINARY,               /* this nonsense is ignored.
                                   all data is treated as binary */
    NAME,                       /* used for pathnames */
    SIZE,                       /* size of data */
    VOLUME,                     /* volume indicator for filesystem initialization */
    DISKLOCK
} pjl_token_type_t;

/* lookup table to map strings to pjl tokens */
typedef struct pjl_lookup_table_s
{
    char pjl_string[PJL_STRING_LENGTH + 1];
    pjl_token_type_t pjl_token;
} pjl_lookup_table_t;

static const pjl_lookup_table_t pjl_table[] = {
    {"@PJL", PREFIX},
    {"SET", SET},
    {"DEFAULT", DEFAULT},
    {"INITIALIZE", INITIALIZE},
    {"=", EQUAL},
    {"DINQUIRE", DINQUIRE},
    {"INQUIRE", INQUIRE},
    {"ENTER", ENTER},
    /* File system related variables */
    {"FSDOWNLOAD", FSDOWNLOAD},
    {"FSAPPEND", FSAPPEND},
    {"FSDELETE", FSDELETE},
    {"FSDIRLIST", FSDIRLIST},
    {"FSINIT", FSINIT},
    {"FSMKDIR", FSMKDIR},
    {"FSQUERY", FSQUERY},
    {"FSUPLOAD", FSUPLOAD},
    {"FORMAT:BINARY", FORMATBINARY},    /* this nonsense is ignored.
                                           all data is treated as binary */
    {"NAME", NAME},             /* used for pathnames */
    {"SIZE", SIZE},             /* size of data */
    {"VOLUME", VOLUME},         /* used for volume name */
    {"ENTRY", ENTRY},
    {"COUNT", COUNT},
    {"OFFSET", OFFSET},
    {"DISKLOCK", DISKLOCK},
    {"", (pjl_token_type_t) 0 /* don't care */ }
};

#include "gdevpxen.h"

#define PJLMEDIA(ms, mstr, res, w, h) \
    { mstr, w, h },
static const struct
{
    const char *media_name;
    float width, height;
} pjl_media[] = {
    px_enumerate_media(PJLMEDIA)
};

/* permenant soft font slots - bit n is the n'th font number. */
#define MAX_PERMANENT_FONTS 256 /* multiple of 8 */
unsigned char pjl_permanent_soft_fonts[MAX_PERMANENT_FONTS / 8];

/* ----- private functions and definitions ------------ */

/* forward declaration */
static int pjl_set(pjl_parser_state_t * pst, char *variable, char *value,
                   bool defaults);

/* lookup a paper size and return the index in the media return letter
   if no match. */

/* somewhat awkward,  */
#define LETTER_PAPER_INDEX 1

static int
pjl_get_media_index(const char *paper)
{
    int i;

    for (i = 0; i < countof(pjl_media); i++)
        if (!pjl_compare(paper, pjl_media[i].media_name))
            return i;
    return LETTER_PAPER_INDEX;
}

/* calculate the number of lines per page as a function of page
   length */
static int
pjl_calc_formlines_new_page_size(int page_length)
{

    /* note the units are 300 dpi units as pcl traditional
       documentation dictates.  This is not properly documented in the
       technical reference manual but the formula appears to be:
       formlines = ((page_length - 300 dots) / 50.0 dots) 50.0 dots
       corresponds with the default pcl 6 lines per inch and 300 with
       1 inch of margin - so the empirical results look plausible.
     */

    double formlines = (page_length - 300.0) / 50.0;

    return (int)(formlines + 0.5);
}

/* handle pjl variables which affect the state of other variables - we
   don't handle all of these yet.  NB not complete. */
static void
pjl_side_effects(pjl_parser_state_t * pst, char *variable, char *value,
                 bool defaults)
{
    if (!pjl_compare(variable, "PAPER") ||
        !pjl_compare(variable, "ORIENTATION")) {

        pjl_envir_var_t *table = (defaults ? pst->defaults : pst->envir);
        int indx = pjl_get_media_index(table[FDEF_PAPER_INDX].value);
        int page_length = (!pjl_compare(variable, "ORIENTATION") &&
                           !pjl_compare(value, "LANDSCAPE") ?
                           (int)(pjl_media[indx].width) :
                           (int)(pjl_media[indx].height));
        int formlines = pjl_calc_formlines_new_page_size(page_length);
        pjl_envir_var_t var;

        gs_sprintf(var.value, "%d", formlines);
        pjl_set(pst, (char *)"FORMLINES", var.value, defaults);
    }
    /* fill in other side effects here */
    return;
}

/* set a pjl environment or default variable. */
static int
pjl_set(pjl_parser_state_t * pst, char *variable, char *value, bool defaults)
{
    pjl_envir_var_t *table = (defaults ? pst->defaults : pst->envir);
    int i;

    if (defaults)               /* default also sets current environment. */
        pjl_set(pst, variable, value, false);

    for (i = 0; table[i].var[0]; i++)
        if (!pjl_compare(table[i].var, variable)) {
            /* set the value */
            strcpy(table[i].value, value);
            /* set any side effects of setting the value */
            pjl_side_effects(pst, variable, value, defaults);
            return 1;
        }
    /* didn't find variable */
    return 0;
}

/* get next token from the command line buffer */
static pjl_token_type_t
pjl_get_token(pjl_parser_state_t * pst, char token[])
{
    int c;
    int start_pos;
    /* skip any whitespace if we need to.  */
    while ((c = pst->line[pst->pos]) == ' ' || c == '\t')
        pst->pos++;

    /* special case to allow = with no intevervening spaces between
       lhs and rhs */
    if (c == '=') {
        pst->pos++;
        return EQUAL;
    }

    /* set the starting position */
    start_pos = pst->pos;

    /* end of line reached; null shouldn't happen but we check anyway */
    if (c == '\0' || c == '\n')
        return DONE;

    /* check for a quoted string.  It should not span a line */
    if (c == '"') {
        pst->pos++;
        while ((c = pst->line[pst->pos]) != '"' && c != '\0' && c != '\n')
            pst->pos++;
        /* this routine doesn't yet support real error handling - here
           we should check if c == '"' */
        if (c == '"')
            pst->pos++;
        else
            return DONE;
    } else {
        /* set the ptr to the next delimeter. */
        while ((c = pst->line[pst->pos]) != ' ' &&
               c != '\t' && c != '\r' && c != '\n' && c != '=' && c != '\0')
            pst->pos++;
    }

    /* build the token */
    {
        int slength = pst->pos - start_pos;
        int i;

        /* we allow = to special case for allowing
           token doesn't fit or is empty */
        if ((slength > PJL_STRING_LENGTH) || slength == 0)
            return DONE;
        /* now the string can be safely copied */
        strncpy(token, &pst->line[start_pos], slength);
        token[slength] = '\0';

        /* for known tokens */
        for (i = 0; pjl_table[i].pjl_string[0]; i++)
            if (!pjl_compare(pjl_table[i].pjl_string, token))
                return pjl_table[i].pjl_token;

        /* NB add other cases here */
        /* check for variables that we support */
        for (i = 0; pst->envir[i].var[0]; i++)
            if (!pjl_compare(pst->envir[i].var, token))
                return VARIABLE;

        /* NB assume this is a setting yuck */
        return SETTING;
    }
    /* shouldn't happen */
    return DONE;
}

/* check if fonts exist in the current font source path */
static char *
pjl_check_font_path(char *path_list, gs_memory_t * mem)
{
    /* lookup a font path and check if any files (presumably fonts are
       present) */
    char tmp_path[PJL_PATH_NAME_LENGTH + 1];
    char *tmp_pathp = tmp_path, *tplast = NULL;
    const char pattern[] = "*";
    char tmp_path_and_pattern[PJL_PATH_NAME_LENGTH + 1 + 1];    /* pattern + null */
    char *dirname;
    char fontfilename[MAXPATHLEN + 1];

    /* make a tmp copy of the colon delimited path */
    strcpy(tmp_path, path_list);
    /* for each path search for fonts.  If we find them return we only
       check if the directory resource has files without checking if
       the files are indeed fonts. */
    while ((dirname = gs_strtok(tmp_pathp, ";", &tplast)) != NULL) {
        file_enum *fe;

        strcpy(tmp_path_and_pattern, dirname);
        strcat(tmp_path_and_pattern, pattern);

        fe = gs_enumerate_files_init(tmp_path_and_pattern,
                                     strlen(tmp_path_and_pattern), mem);
        if (fe == NULL
            ||
            (gs_enumerate_files_next(fe, fontfilename, PJL_PATH_NAME_LENGTH))
            == -1) {
            tmp_pathp = NULL;
        } else {
            /* wind through the rest of the files.  This should close
               things up as well.  All we need to do is clean up but
               gs_enumerate_files_close() does not close the current
               directory */
            while (1) {
                int fstatus =
                    (int)gs_enumerate_files_next(fe, fontfilename,
                                                 PJL_PATH_NAME_LENGTH);
                /* we don't care if the file does not fit (return +1) */
                if (fstatus == -1)
                    break;
            }
            /* NB fix me - replace : separated path with real path.
               We should do this elsewhere */
            strcpy(path_list, dirname);
            return path_list;
        }
    }
    return NULL;
}

/* initilize both pjl state and default environment to default font
   number if font resources are present.  Note we depend on the PDL
   (pcl) to provide information about 'S' permanent soft fonts.  For
   all other resources we check for filenames which should correspond
   to fonts. */
static void
pjl_reset_fontsource_fontnumbers(pjl_parser_state_t * pst)
{
    char default_font_number[] = "0";   /* default number if resources are present */
    gs_memory_t *mem = pst->mem;
    int i;

    for (i = 0; pst->font_defaults[i].designator[0]; i++) {
        if (pjl_check_font_path(pst->font_defaults[i].pathname, mem))
            strcpy(pst->font_defaults[i].fontnumber, default_font_number);
        if (pjl_check_font_path(pst->font_envir[i].pathname, mem))
            strcpy(pst->font_envir[i].fontnumber, default_font_number);
    }
}

/* Strips off extra quotes '"'
 * and changes pjl volume from 0: to makefile specifed PJL_VOLUME_0 directory
 * and translates '\\' to '/'
 * result in fnamep,
 * ie: ""0:\\dir\subdir\file"" --> "PJL_VOLUME_0/dir/subdir/file"
 */
static void
pjl_parsed_filename_to_string(char *fnamep, const char *pathname)
{
    int i;
    int size;

    *fnamep = 0;                /* in case of bad input */
    if (pathname == 0 || pathname[0] != '"' || strlen(pathname) < 3)
        return;                 /* bad input pjl file */

    if (pathname[1] == '0' && pathname[2] == ':') {
        /* copy pjl_volume string in */
        strncpy(fnamep, PJL_VOLUME_0, strlen(PJL_VOLUME_0));
        fnamep += strlen(PJL_VOLUME_0);
    } else if (pathname[1] == '1' && pathname[2] == ':') {
        /* copy pjl_volume string in */
        strncpy(fnamep, PJL_VOLUME_1, strlen(PJL_VOLUME_1));
        fnamep += strlen(PJL_VOLUME_1);
    } else
        return;                 /* bad input pjl file */

    /* the pathname parsed has whatever quoting mechanism was used
     * remove quotes, use forward slash, copy rest.
     */
    size = strlen(pathname);

    for (i = 3; i < size; i++) {
        if (pathname[i] == '\\')
            *fnamep++ = '/';
        else if (pathname[i] != '"')
            *fnamep++ = pathname[i];
        /* else it is a quote skip it */
    }
    /* NULL terminate */
    *fnamep = '\0';
}

/* Verify a file write operation is ok.  The filesystem must be 0: or
   1:, no other pjl files can have pending writes, and the pjl
   disklock state variable must be false */
static int
pjl_verify_file_operation(pjl_parser_state_t * pst, char *fname)
{
    /* make sure we are playing in the pjl sandbox */
    if (0 != strncmp(PJL_VOLUME_0, fname, strlen(PJL_VOLUME_0))
        && 0 != strncmp(PJL_VOLUME_1, fname, strlen(PJL_VOLUME_1))) {
        dmprintf1(pst->mem, "illegal path name %s\n", fname);
        return -1;
    }
    /* make sure we are not currently writing to a file.
       Simultaneously file writing is not supported */
    if (pst->bytes_to_write || pst->fp)
        return -1;

    /* no operation if disklocak is enabled */
    if (!pjl_compare(pjl_get_envvar(pst, "disklock"), "on"))
        return -1;
    /* ok */
    return 0;
}

/* debugging procedure to warn about writing to an extant file */
static void
pjl_warn_exists(const gs_memory_t * mem, char *fname)
{
    FILE *fpdownload;

    /* issue a warning if the file exists */
    if ((fpdownload = gp_fopen(fname, gp_fmode_rb)) != NULL) {
        fclose(fpdownload);
        dmprintf1(mem, "warning file exists overwriting %s\n", fname);
    }
}

/* open a file for writing or appending */
static FILE *
pjl_setup_file_for_writing(pjl_parser_state_t * pst, char *pathname, int size,
                           bool append)
{
    FILE *fp;
    char fname[MAXPATHLEN];

    pjl_parsed_filename_to_string(fname, pathname);
    if (pjl_verify_file_operation(pst, fname) < 0)
        return NULL;
    pjl_warn_exists(pst->mem, fname);
    {
        char fmode[4];

        strcpy(fmode, gp_fmode_wb);
        if (append)
            strcat(fmode, "+");
        if ((fp = gp_fopen(fname, gp_fmode_wb)) == NULL) {
            dmprintf(pst->mem, "warning file open for writing failed\n");
            return NULL;
        }
    }
    return fp;
}

/* set up the state to download date to a pjl file */
static int
pjl_set_fs_download_state(pjl_parser_state_t * pst, char *pathname, int size)
{
    /* somethink is wrong if the state indicates we are already writing to a file */
    FILE *fp =
        pjl_setup_file_for_writing(pst, pathname, size, false /* append */ );
    if (fp == NULL)
        return -1;
    pst->fp = fp;
    pst->bytes_to_write = size;
    return 0;
}

/* set up the state to append subsequent data from the input stream to
   a file */
static int
pjl_set_append_state(pjl_parser_state_t * pst, char *pathname, int size)
{
    FILE *fp =
        pjl_setup_file_for_writing(pst, pathname, size, true /* append */ );
    if (fp == NULL)
        return -1;
    pst->fp = fp;
    pst->bytes_to_write = size;
    return 0;
}

/* create a pjl volume, this should create the volume 0: or 1: we
   simply create a directory with the volume name. */
static int
pjl_fsinit(pjl_parser_state_t * pst, char *pathname)
{
    char fname[MAXPATHLEN];

    pjl_parsed_filename_to_string(fname, pathname);
    if (pjl_verify_file_operation(pst, fname) < 0)
        return -1;
    return mkdir(fname, 0777);
}

/* make a pjl directory */
static int
pjl_fsmkdir(pjl_parser_state_t * pst, char *pathname)
{
    char fname[MAXPATHLEN];

    pjl_parsed_filename_to_string(fname, pathname);
    if (pjl_verify_file_operation(pst, fname) < 0)
        return -1;
    return mkdir(fname, 0777);
}

/* query a file in the pjl sandbox */
static int
pjl_fsquery(pjl_parser_state_t * pst, char *pathname)
{
    /* not implemented */
    return -1;
}

/* Upload a file from the pjl sandbox */
static int
pjl_fsupload(pjl_parser_state_t * pst, char *pathname, int offset, int size)
{
    /* not implemented */
    return -1;
}

/* search pathname for filename return a match in result.  result
   should be a 0 length string upon calling this routine.  If a match
   is found result will hold the matching path and filename.  Thie
   procedure recursively searches the directory tree "pathname" for
   "filename" */
static int
pjl_search_for_file(pjl_parser_state_t * pst, char *pathname, char *filename,
                    char *result)
{
    file_enum *fe;
    char fontfilename[MAXPATHLEN];
    struct stat stbuf;

    /* should check length */
    strcpy(fontfilename, pathname);
    strcat(fontfilename, "/*");
    fe = gs_enumerate_files_init(fontfilename, strlen(fontfilename),
                                 pst->mem);
    if (fe) {
        do {
            uint fstatus =
                gs_enumerate_files_next(fe, fontfilename,
                                        PJL_PATH_NAME_LENGTH);
            /* done */
            if (fstatus == ~(uint) 0)
                return 0;
            fontfilename[fstatus] = '\0';
            if (fontfilename[fstatus - 1] != '.') {     /* skip over . and .. */
                /* a directory */
                if ((stat(fontfilename, &stbuf) >= 0) && stat_is_dir(stbuf))
                    pjl_search_for_file(pst, fontfilename, filename, result);
                else /* a file */
                if (!strcmp(strrchr(fontfilename, '/') + 1, filename))
                    strcpy(result, fontfilename);
            }

        } while (1);
    }
    /* not implemented */
    return -1;
}

static int
pjl_fsdirlist(pjl_parser_state_t * pst, char *pathname, int entry, int count)
{
    file_enum *fe;
    char fontfilename[MAXPATHLEN];

    pjl_parsed_filename_to_string(fontfilename, pathname);
    /* if this is a directory add * for the directory listing NB fix */
    strcat(fontfilename, "/*");
    fe = gs_enumerate_files_init(fontfilename, strlen(fontfilename),
                                 pst->mem);
    if (fe) {
        do {
            uint fstatus =
                gs_enumerate_files_next(fe, fontfilename,
                                        PJL_PATH_NAME_LENGTH);
            /* done */
            if (fstatus == ~(uint) 0)
                return 0;
            fontfilename[fstatus] = '\0';
            /* NB - debugging output only */
            dmprintf1(pst->mem, "%s\n", fontfilename);
        } while (1);
    }
    /* should not get here */
    return -1;
}

inline static int
pjl_write_remaining_data(pjl_parser_state_t * pst, const byte ** pptr,
                         const byte ** pplimit)
{
    const byte *ptr = *pptr;
    const byte *plimit = *pplimit;
    uint avail = plimit - ptr;
    uint bytes_written = min(avail, pst->bytes_to_write);

    if (fwrite(ptr, 1, bytes_written, pst->fp) != bytes_written) {
        /* try to close the file before failing */
        fclose(pst->fp);
        pst->fp = NULL;
        return -1;
    }
    pst->bytes_to_write -= bytes_written;
    if (pst->bytes_to_write == 0) {     /* done */
        fclose(pst->fp);
        pst->fp = NULL;
    }
    /* update stream pointer */
    *pptr += bytes_written;
    return 0;
}

static int
pjl_delete_file(pjl_parser_state_t * pst, char *pathname)
{
    char fname[MAXPATHLEN];

    pjl_parsed_filename_to_string(fname, pathname);
    if (pjl_verify_file_operation(pst, fname) < 0)
        return -1;
    return unlink(fname);
}

/* handle pattern foo = setting, e.g. volume = "0:", name = 0:]pcl.
   the setting will be returned in "token" if successful.  Return 0
   for success and -1 if we fail */
static int
pjl_get_setting(pjl_parser_state_t * pst, pjl_token_type_t tok, char *token)
{
    pjl_token_type_t lhs = pjl_get_token(pst, token);

    if (lhs != tok)
        return -1;
    if ((tok = pjl_get_token(pst, token)) != EQUAL)
        return -1;
    if ((tok = pjl_get_token(pst, token)) != SETTING)
        return -1;
    return 0;
}

/* parse and set up state for one line of pjl commands */
static int
pjl_parse_and_process_line(pjl_parser_state_t * pst)
{
    pjl_token_type_t tok;
    char token[PJL_STRING_LENGTH + 1] = { 0 };
    char pathname[MAXPATHLEN];

    /* reset the line position to the beginning of the line */
    pst->pos = 0;
    /* all pjl commands start with the pjl prefix @PJL */
    if ((tok = pjl_get_token(pst, token)) != PREFIX)
        return -1;
    /* NB we should check for required and optional used of whitespace
       but we don't see PJLTRM 2-6 PJL Command Syntax and Format. */
    while ((tok = pjl_get_token(pst, token)) != DONE) {
        switch (tok) {
            case SET:
            case DEFAULT:
                {
                    bool defaults;

                  var:defaults = (tok == DEFAULT);
                    /* NB we skip over lparm and search for the variable */
                    while ((tok = pjl_get_token(pst, token)) != DONE)
                        if (tok == VARIABLE) {
                            char variable[PJL_STRING_LENGTH + 1];

                            strcpy(variable, token);
                            if (((tok = pjl_get_token(pst, token)) == EQUAL)
                                && (tok =
                                    pjl_get_token(pst, token)) == SETTING) {
                                /* an unfortunate side effect - we have to
                                   identify FORMLINES being set here, for
                                   the benefit of PCL, see the
                                   documentation to the function
                                   pcursor.c:pcl_vmi_default() for
                                   details. */
                                if (!pjl_compare(variable, "FORMLINES"))
                                    pjl_set(pst, (char *)"FORMLINES_SET",
                                            (char *)"on", defaults);
                                return pjl_set(pst, variable, token,
                                               defaults);
                            } else
                                return -1;      /* syntax error */
                        } else
                            continue;
                    return 0;
                }
            case INITIALIZE:
                /* set the user default environment to the factory default environment */
                memcpy(pst->defaults, &pjl_factory_defaults,
                       sizeof(pjl_factory_defaults));
                memcpy(pst->font_defaults, &pjl_fontsource_table,
                       sizeof(pjl_fontsource_table));
                pjl_reset_fontsource_fontnumbers(pst);
                return 0;
                /* set the current environment to the user default environment */
            case RESET:
                memcpy(pst->envir, pst->defaults,
                       sizeof(pjl_factory_defaults));
                memcpy(pst->font_envir, pst->font_defaults,
                       sizeof(pjl_fontsource_table));
                return 0;
            case ENTER:
                /* there is no setting for the default language */
                tok = SET;
                goto var;
            case FSDOWNLOAD:{
                    /* consume and ignore FORMAT:BINARY foolishness. if it is
                       present or search for the name */
                    int size;

                    /* ignore format binary stuff */
                    if ((tok = pjl_get_token(pst, token)) == FORMATBINARY) {
                        ;
                    }
                    if (pjl_get_setting(pst, NAME, token) < 0)
                        return -1;
                    strcpy(pathname, token);
                    if (pjl_get_setting(pst, SIZE, token) < 0)
                        return -1;
                    size = pjl_vartoi(token);
                    return pjl_set_fs_download_state(pst, pathname, size);
                }
            case FSAPPEND:{
                    int size;

                    if ((tok = pjl_get_token(pst, token)) == FORMATBINARY) {
                        ;
                    }
                    if (pjl_get_setting(pst, NAME, token) < 0)
                        return -1;
                    strcpy(pathname, token);
                    if (pjl_get_setting(pst, SIZE, token) < 0)
                        return -1;
                    size = pjl_vartoi(token);
                    return pjl_set_append_state(pst, pathname, size);
                }
            case FSDELETE:
                if (pjl_get_setting(pst, NAME, token) < 0)
                    return -1;
                strcpy(pathname, token);
                return pjl_delete_file(pst, pathname);
            case FSDIRLIST:{
                    int entry;

                    int count;

                    if (pjl_get_setting(pst, NAME, token) < 0)
                        return -1;
                    strcpy(pathname, token);
                    if (pjl_get_setting(pst, ENTRY, token) < 0)
                        return -1;
                    entry = pjl_vartoi(token);
                    if (pjl_get_setting(pst, COUNT, token) < 0)
                        return -1;
                    count = pjl_vartoi(token);
                    return pjl_fsdirlist(pst, pathname, entry, count);
                }
            case FSINIT:
                if (pjl_get_setting(pst, VOLUME, token) < 0)
                    return -1;
                strcpy(pathname, token);
                return pjl_fsinit(pst, pathname);
            case FSMKDIR:
                if (pjl_get_setting(pst, NAME, token) < 0)
                    return -1;
                strcpy(pathname, token);
                return pjl_fsmkdir(pst, pathname);
            case FSQUERY:
                if (pjl_get_setting(pst, NAME, token) < 0)
                    return -1;
                strcpy(pathname, token);
                return pjl_fsquery(pst, pathname);
            case FSUPLOAD:{
                    int size;

                    int offset;

                    if ((tok = pjl_get_token(pst, token)) == FORMATBINARY) {
                        ;
                    }
                    if (pjl_get_setting(pst, NAME, token) < 0)
                        return -1;
                    strcpy(pathname, token);
                    if (pjl_get_setting(pst, OFFSET, token) < 0)
                        return -1;
                    offset = pjl_vartoi(token);
                    if (pjl_get_setting(pst, SIZE, token) < 0)
                        return -1;
                    size = pjl_vartoi(token);
                    return pjl_fsupload(pst, pathname, size, offset);
                }
            default:
                return -1;
        }
    }
    return (tok == DONE ? 0 : -1);
}

/* get a file from 0: or 1: volume */
static FILE *
get_fp(pjl_parser_state_t * pst, char *name)
{
    char result[MAXPATHLEN];

    /* 0: */
    result[0] = '\0';
    pjl_search_for_file(pst, (char *)PJL_VOLUME_0, name, result);
    if (result[0] == '\0') {
        /* try 1: */
        pjl_search_for_file(pst, (char *)PJL_VOLUME_1, name, result);
        if (result[0] == '\0')
            return 0;
    }
    return gp_fopen(result, gp_fmode_rb);
}

/* scan for a named resoource in the pcl sandbox 0: or 1: and return
   the size of the object.  We do not distinguish between empty and
   non-existant files */
long int
pjl_get_named_resource_size(pjl_parser_state_t * pst, char *name)
{
    long int size;
    FILE *fp = get_fp(pst, name);

    if (fp == NULL)
        return 0;
    fseek(fp, 0L, SEEK_END);
    size = ftell(fp);
    fclose(fp);
    return size;
}

/* get the contents of a file on 0: or 1: and return the result in the
   client allocated memory */
int
pjl_get_named_resource(pjl_parser_state * pst, char *name, byte * data)
{
    long int size;
    FILE *fp = get_fp(pst, name);

    if (fp == NULL)
        return 0;
    fseek(fp, 0L, SEEK_END);
    size = ftell(fp);
    rewind(fp);
    if (size != fread(data, 1, size, fp)) {
        fclose(fp);
        return -1;
    }
    return 0;
}

/* set the initial environment to the default environment, this should
   be done at the beginning of each job */
void
pjl_set_init_from_defaults(pjl_parser_state_t * pst)
{
    memcpy(pst->envir, pst->defaults, sizeof(pjl_factory_defaults));
    memcpy(pst->font_envir, pst->font_defaults, sizeof(pjl_fontsource_table));
}

void
pjl_set_next_fontsource(pjl_parser_state_t * pst)
{
    int current_source;
    pjl_envvar_t *current_font_source = pjl_get_envvar(pst, "fontsource");

    /* find the index of the current resource then work backwards
       until we find font resources.  We assume the internal source
       will have fonts */
    for (current_source = 0; pst->font_envir[current_source].designator[0];
         current_source++)
        if (!pjl_compare(pst->font_envir[current_source].designator,
                         current_font_source))
            break;

    /* next resource is not internal 'I' */
    if (current_source != 0) {
        while (current_source > 0) {
            current_source--;   /* go to next fontsource */
            /* check if it contains fonts, i.e. fontnumber != null */
            if (pst->font_envir[current_source].fontnumber[0])
                break;
        }
    }
    /* set both default and environment font source, the spec is not clear
       about this */
    pjl_set(pst, (char *)"fontsource",
            pst->font_envir[current_source].designator, true);
    pjl_set(pst, (char *)"fontsource",
            pst->font_defaults[current_source].designator, false);
}

/* get a pjl environment variable from the current environment - not
   the user default environment */
pjl_envvar_t *
pjl_get_envvar(pjl_parser_state * pst, const char *pjl_var)
{
    int i;
    pjl_envir_var_t *env = pst->envir;

    /* lookup up the value */
    for (i = 0; env[i].var[0]; i++)
        if (!pjl_compare(env[i].var, pjl_var)) {
            return env[i].value;
        }
    return NULL;
}

/*
 * Detect illegal characters when preprocessing each line of PJL.
 */
static inline bool
legal_pjl_char(const byte ch)
{
    return (ch >= 32 || isspace(ch));
}

/* -- public functions - see pjparse.h for interface documentation -- */

/* Process a buffer of PJL commands. */
int
pjl_process(pjl_parser_state * pst, void *pstate, stream_cursor_read * pr)
{
    const byte *p = pr->ptr;
    const byte *rlimit = pr->limit;
    int code = 0;

    /* first check if we are writing data to a file as part of the
       file system commands */

    while (p < rlimit) {
        if (pst->bytes_to_write != 0) {
            p++;
            if (pjl_write_remaining_data(pst, &p, &rlimit) == 0) {
                p--;
                continue;
            } else
                return -1;
        }

        if (pst->pos == 0) {    /* Look ahead for the @PJL prefix or a UEL. */
            uint avail = rlimit - p;

            if (!memcmp(p + 1, "\033%-12345X", min(avail, 9))) {        /* Might be a UEL. */
                if (avail < 9) {        /* Not enough data to know yet. */
                    break;
                }
                /* Skip the UEL and continue. */
                p += 9;
                continue;
            } else if (!memcmp(p + 1, "@PJL", min(avail, 4))) { /* Might be PJL. */
                if (avail < 4) {        /* Not enough data to know yet. */
                    break;
                }
                /* Definitely a PJL command. */
            } else {            /* Definitely not PJL. */
                code = 1;
                break;
            }
        }
        if (p[1] == '\n') {
            ++p;
            /* null terminate, parse and set the pjl state */
            pst->line[pst->pos] = '\0';
            pjl_parse_and_process_line(pst);
            pst->pos = 0;
            continue;
        }
        
        if (!legal_pjl_char(p[1])) {
            code = 1;
            break;
        }

        /* Copy the PJL line into the parser's line buffer. */
        /* Always leave room for a terminator. */
        if (pst->pos < countof(pst->line) - 1)
            pst->line[pst->pos] = p[1], pst->pos++;
        ++p;
    }
    pr->ptr = p;
    return code;
}

/* Discard the remainder of a job.  Return true when we reach a UEL. */
/* The input buffer must be at least large enough to hold an entire UEL. */
bool
pjl_skip_to_uel(stream_cursor_read * pr)
{
    const byte *p = pr->ptr;
    const byte *rlimit = pr->limit;

    for (; p < rlimit; ++p)
        if (p[1] == '\033') {
            uint avail = rlimit - p;

            if (memcmp(p + 1, "\033%-12345X", min(avail, 9)))
                continue;
            if (avail < 9)
                break;
            pr->ptr = p + 9;
            return true;
        }
    pr->ptr = p;
    return false;
}

/* PJL symbol set environment variable -> pcl symbol set numbers.
   This probably should not be defined here :-( */
static const struct
{
    const char *symname;
    const char *pcl_selectcode;
} symbol_sets[] = {
    {"ROMAN8", "8U"},
    {"ISOL1", "0N"},
    {"ISOL2", "2N"},
    {"ISOL5", "5N"},
    {"PC8", "10U"},
    {"PC8DN", "11U"},
    {"PC850", "12U"},
    {"PC852", "17U"},
    {"PC8TK", "9T"},             /* pc-8 turkish ?? not sure */
    {"WINL1", "9U"},
    {"WINL2", "9E"},
    {"WINL5", "5T"},
    {"DESKTOP", "7J"},
    {"PSTEXT", "10J"},
    {"VNINTL", "13J"},
    {"VNUS", "14J"},
    {"MSPUBL", "6J"},
    {"MATH8", "8M"},
    {"PSMATH", "5M"},
    {"VNMATH", "6M"},
    {"PIFONT", "15U"},
    {"LEGAL", "1U"},
    {"ISO4", "1E"},
    {"ISO6", "0U"},
    {"ISO11", "0S"},
    {"ISO15", "0I"},
    {"ISO17", "2S"},
    {"ISO21", "1G"},
    {"ISO60", "OD"},
    {"ISO69", "1F"},
    {"WIN30", NULL},             /* don't know */
    {"WIN31J", NULL},            /* don't know */
    {"GB2312", NULL},            /* don't know */
    {NULL, NULL}
};

/* map a pjl symbol table name to a pcl symbol table name */
int
pjl_map_pjl_sym_to_pcl_sym(const char *symname)
{
    int i;

    for (i = 0; symbol_sets[i].symname; i++)
        if (!pjl_compare(symname, symbol_sets[i].symname)) {
            /* convert the character code to it's integer
               representation.  NB peculiar code! */
            char pcl_symbol[4], chr;
            int char_pos;

            strcpy(pcl_symbol, symbol_sets[i].pcl_selectcode);
            char_pos = strlen(pcl_symbol) - 1;
            chr = pcl_symbol[char_pos];
            pcl_symbol[char_pos] = '\0';
            return (atoi(pcl_symbol) << 5) + chr - 64;
        }
    return -1;
}

/* environment variable to integer */
int
pjl_vartoi(const pjl_envvar_t * s)
{
    return atoi(s);
}

/* environment variable to float */
double
pjl_vartof(const pjl_envvar_t * s)
{
    return atof(s);
}

/* convert a pjl font source to a pathname */
char *
pjl_fontsource_to_path(const pjl_parser_state * pjls,
                       const pjl_envvar_t * fontsource)
{
    int i;

    /* if an environment variable is set we use it, otherwise use the PJL
       machinery */
    if (pjls->environment_font_path != NULL)
        return pjl_check_font_path(pjls->environment_font_path, pjls->mem);
    for (i = 0; pjls->font_envir[i].designator[0]; i++)
        if (!pjl_compare(pjls->font_envir[i].designator, fontsource))
            return pjl_check_font_path(pjls->font_envir[i].pathname,
                                       pjls->mem);
    return NULL;
}

/* Create and initialize a new state. */
pjl_parser_state *
pjl_process_init(gs_memory_t * mem)
{
    pjl_parser_state_t *pjlstate = (pjl_parser_state *) gs_alloc_bytes(mem,
                                                                       sizeof
                                                                       (pjl_parser_state_t),
                                                                       "pjl_state");
    pjl_envir_var_t *pjl_env = (pjl_envir_var_t *) gs_alloc_bytes(mem,
                                                                  sizeof
                                                                  (pjl_factory_defaults),
                                                                  "pjl_envir");
    pjl_envir_var_t *pjl_def = (pjl_envir_var_t *) gs_alloc_bytes(mem,
                                                                  sizeof
                                                                  (pjl_factory_defaults),
                                                                  "pjl_defaults");
    pjl_fontsource_t *pjl_fontenv = (pjl_fontsource_t *) gs_alloc_bytes(mem,
                                                                        sizeof
                                                                        (pjl_fontsource_table),
                                                                        "pjl_font_envir");
    pjl_fontsource_t *pjl_fontdef = (pjl_fontsource_t *) gs_alloc_bytes(mem,
                                                                        sizeof
                                                                        (pjl_fontsource_table),
                                                                        "pjl_font_defaults");

    if (pjlstate == NULL || pjl_env == NULL || pjl_def == NULL)
        return NULL;            /* should be fatal so we don't bother piecemeal frees */

    /* check for an environment variable */
    {
        int pathlen, code;

        /* The environment variable exists if the function fails to
           fit in the null - odd but it works.  We allow an
           environment variable to override the font default PJL font
           path for desktop setups */
        pathlen = 0;
        if ((code = gp_getenv("PCLFONTSOURCE", (char *)0, &pathlen)) < 0) {
            char *path =
                (char *)gs_alloc_bytes(mem, pathlen, "pjl_font_path");
            /* if the allocation fails we use the pjl fontsource */
            if (path == NULL)
                pjlstate->environment_font_path = NULL;
            else {
                gp_getenv("PCLFONTSOURCE", path, &pathlen);     /* can't fail */
                pjlstate->environment_font_path = path;
            }
        } else                  /* environmet variable does not exist use pjl fontsource */
            pjlstate->environment_font_path = NULL;
    }
    pjlstate->defaults = pjl_def;
    pjlstate->envir = pjl_env;
    pjlstate->font_envir = pjl_fontenv;
    pjlstate->font_defaults = pjl_fontdef;
    /* initialize the default and initial pjl environment.  We assume
       that these are the same layout as the factory defaults. */
    memcpy(pjlstate->defaults, pjl_factory_defaults,
           sizeof(pjl_factory_defaults));
    memcpy(pjlstate->envir, pjlstate->defaults, sizeof(pjl_factory_defaults));
    /* initialize the font repository data as well */
    memcpy(pjlstate->font_defaults, pjl_fontsource_table,
           sizeof(pjl_fontsource_table));
    memcpy(pjlstate->font_envir, pjl_fontsource_table,
           sizeof(pjl_fontsource_table));
    /* initialize the current position in the line array and bytes pending */
    pjlstate->bytes_to_read = 0;
    pjlstate->bytes_to_write = 0;
    pjlstate->fp = 0;
    /* line pos */
    pjlstate->pos = 0;
    pjlstate->mem = mem;
    /* initialize available font sources */
    pjl_reset_fontsource_fontnumbers(pjlstate);
    {
        int i;

        for (i = 0; i < countof(pjl_permanent_soft_fonts); i++)
            pjl_permanent_soft_fonts[i] = 0;
    }
    return (pjl_parser_state *) pjlstate;
}

/* case insensitive comparison of two null terminated strings. */
int
pjl_compare(const pjl_envvar_t * s1, const char *s2)
{
    for (; toupper(*s1) == toupper(*s2); ++s1, ++s2)
        if (*s1 == '\0')
            return (0);
    return 1;
}

/* free all memory associated with the PJL state */
void
pjl_process_destroy(pjl_parser_state * pst, gs_memory_t * mem)
{
    gs_free_object(mem, pst->font_envir, "pjl_font_envir");
    gs_free_object(mem, pst->font_defaults, "pjl_font_defaults");
    gs_free_object(mem, pst->defaults, "pjl_defaults");
    gs_free_object(mem, pst->envir, "pjl_envir");
    if (pst->environment_font_path)
        gs_free_object(mem, pst->environment_font_path, "pjl_state");
    gs_free_object(mem, pst, "pjl_state");
}

/* delete a permanent soft font */
int
pjl_register_permanent_soft_font_deletion(pjl_parser_state * pst,
                                          int font_number)
{
    if ((font_number > MAX_PERMANENT_FONTS - 1) || (font_number < 0)) {
        dmprintf(pst->mem,
                 "pjparse.c:pjl_register_permanent_soft_font_deletion() bad font number\n");
        return 0;
    }
    /* if the font is present. */
    if ((pjl_permanent_soft_fonts[font_number >> 3]) &
        (128 >> (font_number & 7))) {
        /* set the bit to zero to indicate the fontnumber has been deleted */
        pjl_permanent_soft_fonts[font_number >> 3] &=
            ~(128 >> (font_number & 7));
        /* if the current font source is 'S' and the current font number
           is the highest number, and *any* soft font was deleted or if
           the last font has been removed, set the stage for changing to
           the next priority font source.  BLAME HP not me. */
        {
            bool is_S = !pjl_compare(pjl_get_envvar(pst, "fontsource"), "S");
            bool empty = true;
            int highest_fontnumber = -1;
            int current_fontnumber =
                pjl_vartoi(pjl_get_envvar(pst, "fontnumber"));
            int i;

            /* check for no more fonts and the highest font number.
               NB should look at longs not bits in the loop */
            for (i = 0; i < MAX_PERMANENT_FONTS; i++)
                if ((pjl_permanent_soft_fonts[i >> 3]) & (128 >> (i & 7))) {
                    empty = false;
                    highest_fontnumber = i;
                }
            if (is_S && ((highest_fontnumber == current_fontnumber) || empty)) {
#define SINDEX 4
                pst->font_defaults[SINDEX].fontnumber[0] = '\0';
                pst->font_envir[SINDEX].fontnumber[0] = '\0';
                return 1;
#undef SINDEX
            }
        }
    }
    return 0;
}

/* request that pjl add a soft font and return a pjl font number for
   the font. */
int
pjl_register_permanent_soft_font_addition(pjl_parser_state * pst)
{
    /* Find an empty slot in the table.  We have no HP documentation
       that says how a soft font gets associated with a font number */
    int font_num;
    bool slot_found;

    for (font_num = 0; font_num < MAX_PERMANENT_FONTS; font_num++)
        if (!
            ((pjl_permanent_soft_fonts[font_num >> 3]) &
             (128 >> (font_num & 7)))) {
            slot_found = true;
            break;
        }
    /* yikes, shouldn't happen */
    if (!slot_found) {
        dmprintf(pst->mem,
                 "pjparse.c:pjl_register_permanent_soft_font_addition()\
                 font table full recycling font number 0\n");
        font_num = 0;
    }
    /* set the bit to 1 to indicate the fontnumber has been added */
    pjl_permanent_soft_fonts[font_num >> 3] |= (128 >> (font_num & 7));
    return font_num;
}