about summary refs log tree commit diff
path: root/converter/other/pnmtops.c
blob: 4b56b6a25b3b73bcf9c2915d6aa432cde5f9a926 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
/* pnmtops.c - read a PNM image and produce a PostScript program.

   Copyright information is at end of file.

   We produce two main kinds of Postscript program:

      1) Use built in Postscript filters /ASCII85Decode, /ASCIIHexDecode,
	 /RunLengthDecode, and /FlateDecode;

	 We use methods we learned from Dirk Krause's program Bmeps.
	 Previous versions used raster encoding code based on Bmeps
	 code.  This program does not used any code from Bmeps.

      2) Use our own filters and redefine /readstring .  This is aboriginal
	 Netpbm code, from when Postscript was young.  The filters are
	 nearly identical to /ASCIIHexDecode and /RunLengthDecode.  We
	 use the same raster encoding code with slight modifications.

   (2) is the default.  (1) gives more options, but relies on features
   introduced in Postscript Level 2, which appeared in 1991.  Postcript
   devices made before 1991 can't handle them.  The user selects (1)
   with the -psfilter option.

   We also do a few other bold new things only when the user specifies
   -psfilter, because we're not sure they work for everyone.

   (I actually don't know Postscript, so some of this description, not to
   mention the code, may be totally bogus.)

   NOTE: it is possible to put transparency information in an
   encapsulated Postscript program.  Bmeps does this.  We don't.  It
   might be hard to do, because in Postscript, the transparency information
   goes in separate from the rest of the raster.
*/

#define _BSD_SOURCE  /* Make sure string.h contains strdup() */
#define _XOPEN_SOURCE 500  /* Make sure strdup() is in string.h */
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <assert.h>
#include <string.h>
#ifndef NOFLATE
#include <zlib.h>
#endif

#include "pm_c_util.h"
#include "pam.h"
#include "mallocvar.h"
#include "shhopt.h"
#include "nstring.h"

struct cmdlineInfo {
    /* All the information the user supplied in the command line,
       in a form easy for the program to use.
    */
    const char * inputFileName;  /* Filespecs of input file */
    float        scale;
    unsigned int dpiX;     /* horiz component of DPI option */
    unsigned int dpiY;     /* vert component of DPI option */
    unsigned int width;              /* in 1/72 inch */
    unsigned int height;             /* in 1/72 inch */
    unsigned int mustturn;
    bool         canturn;
    unsigned int rle;
    bool         center;
    unsigned int imagewidth;         /* in 1/72 inch; zero if unspec */
    unsigned int imageheight;        /* in 1/72 inch; zero if unspec */
    unsigned int equalpixels;
    unsigned int bitspersampleSpec;
    unsigned int bitspersample;
    unsigned int setpage;
    bool         showpage;
    unsigned int level;
    unsigned int levelSpec;
    unsigned int psfilter;
    unsigned int flate;
    unsigned int ascii85;
    unsigned int dict;
    unsigned int vmreclaim;
    unsigned int verbose;
};

static bool verbose;



static void
parseDpi(const char *   const dpiOpt, 
         unsigned int * const dpiXP, 
         unsigned int * const dpiYP) {

    char *dpistr2;
    unsigned long int dpiX, dpiY;

    dpiX = strtol(dpiOpt, &dpistr2, 10);
    if (dpistr2 == dpiOpt)
        pm_error("Invalid value for -dpi: '%s'.  Must be either number "
                 "or NxN ", dpiOpt);
    else if (dpiX > INT_MAX)
        pm_error("Invalid value for -dpi: '%s'.  "
                 "Value too large for computation", dpiOpt);
    else {
        if (*dpistr2 == '\0') {
            *dpiXP = dpiX;
            *dpiYP = dpiX;
        } else if (*dpistr2 == 'x') {
            char * dpistr3;

            dpistr2++;  /* Move past 'x' */
            dpiY = strtol(dpistr2, &dpistr3, 10);
            if (dpiY > INT_MAX)
                pm_error("Invalid value for -dpi: '%s'.  "
                         "Value too large for computation", dpiOpt);
            else if (dpistr3 != dpistr2 && *dpistr3 == '\0') {
                *dpiXP = dpiX;
                *dpiYP = dpiY;
            } else {
                pm_error("Invalid value for -dpi: '%s'.  Must be either "
                         "number or NxN", dpiOpt);
            }
        }
    }
}



static void
validateBps_1_2_4_8_12(unsigned int const bitsPerSample) {

    switch (bitsPerSample) {
    case 1:
    case 2:
    case 4:
    case 8:
    case 12:
        break;
    default:
        pm_error("Invalid -bitspersample value: %u.  Must be "
                 "1, 2, 4, 8, or 12", bitsPerSample);
    }
}



static void
validateCompDimension(unsigned int const value,
                      unsigned int const scaleFactor,
                      const char * const vname) {
/*----------------------------------------------------------------------------
  Validate that the image dimension (width or height) 'value' isn't so big
  that in this program's calculations, involving scale factor 'scaleFactor',
  it would cause a register overflow.  If it is, abort the program and refer
  to the offending dimension as 'vname' in the error message.

  Note that this early validation approach (calling this function) means
  the actual computations don't have to be complicated with arithmetic
  overflow checks, so they're easier to read.
-----------------------------------------------------------------------------*/
    if (value > 0) {
        unsigned int const maxWidthHeight = INT_MAX - 2;
        unsigned int const maxScaleFactor = maxWidthHeight / value;

        if (scaleFactor > maxScaleFactor)
            pm_error("%s is too large for compuations: %u", vname, value);
    }
}



static void
parseCommandLine(int argc, const char ** argv,
                 struct cmdlineInfo * const cmdlineP) {

    unsigned int imagewidthSpec, imageheightSpec;
    float imagewidth, imageheight;
    unsigned int center, nocenter;
    unsigned int nosetpage;
    float width, height;
    unsigned int noturn;
    unsigned int showpage, noshowpage;
    const char * dpiOpt;
    unsigned int dpiSpec, scaleSpec, widthSpec, heightSpec;

    optStruct3 opt;
    unsigned int option_def_index = 0;
    optEntry * option_def;

    MALLOCARRAY_NOFAIL(option_def, 100);

    OPTENT3(0, "scale",       OPT_FLOAT, &cmdlineP->scale, &scaleSpec,   0);
    OPTENT3(0, "dpi",         OPT_STRING, &dpiOpt,         &dpiSpec,     0);
    OPTENT3(0, "width",       OPT_FLOAT, &width,           &widthSpec,   0);
    OPTENT3(0, "height",      OPT_FLOAT, &height,          &heightSpec,  0);
    OPTENT3(0, "psfilter",    OPT_FLAG,  NULL, &cmdlineP->psfilter,      0);
    OPTENT3(0, "turn",        OPT_FLAG,  NULL, &cmdlineP->mustturn,      0);
    OPTENT3(0, "noturn",      OPT_FLAG,  NULL, &noturn,                  0);
    OPTENT3(0, "rle",         OPT_FLAG,  NULL, &cmdlineP->rle,           0);
    OPTENT3(0, "runlength",   OPT_FLAG,  NULL, &cmdlineP->rle,           0);
    OPTENT3(0, "ascii85",     OPT_FLAG,  NULL, &cmdlineP->ascii85,       0);
    OPTENT3(0, "center",      OPT_FLAG,  NULL, &center,                  0);
    OPTENT3(0, "nocenter",    OPT_FLAG,  NULL, &nocenter,                0);
    OPTENT3(0, "equalpixels", OPT_FLAG,  NULL, &cmdlineP->equalpixels,   0);
    OPTENT3(0, "imagewidth",  OPT_FLOAT, &imagewidth,  &imagewidthSpec,  0);
    OPTENT3(0, "imageheight", OPT_FLOAT, &imageheight, &imageheightSpec, 0);
    OPTENT3(0, "bitspersample", OPT_UINT, &cmdlineP->bitspersample,
            &cmdlineP->bitspersampleSpec, 0);
    OPTENT3(0, "nosetpage",   OPT_FLAG,  NULL, &nosetpage,               0);
    OPTENT3(0, "setpage",     OPT_FLAG,  NULL, &cmdlineP->setpage,       0);
    OPTENT3(0, "noshowpage",  OPT_FLAG,  NULL, &noshowpage,              0);
    OPTENT3(0, "flate",       OPT_FLAG,  NULL, &cmdlineP->flate,         0);
    OPTENT3(0, "dict",        OPT_FLAG,  NULL, &cmdlineP->dict,          0);
    OPTENT3(0, "vmreclaim",   OPT_FLAG,  NULL, &cmdlineP->vmreclaim,     0);
    OPTENT3(0, "showpage",    OPT_FLAG,  NULL, &showpage,                0);
    OPTENT3(0, "verbose",     OPT_FLAG,  NULL, &cmdlineP->verbose,       0);
    OPTENT3(0, "level",       OPT_UINT, &cmdlineP->level, 
            &cmdlineP->levelSpec,              0);
    
    opt.opt_table = option_def;
    opt.short_allowed = FALSE;
    opt.allowNegNum = FALSE;

    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);

    if (cmdlineP->mustturn && noturn)
        pm_error("You cannot specify both -turn and -noturn");
    if (center && nocenter)
        pm_error("You cannot specify both -center and -nocenter");
    if (showpage && noshowpage)
        pm_error("You cannot specify both -showpage and -noshowpage");
    if (cmdlineP->setpage && nosetpage)
        pm_error("You cannot specify both -setpage and -nosetpage");

    if (!scaleSpec)
        cmdlineP->scale = 1.0;

    if (!widthSpec)
        width = 8.5;

    if (!heightSpec)
        height = 11.0;

    if (dpiSpec)
        parseDpi(dpiOpt, &cmdlineP->dpiX, &cmdlineP->dpiY);
    else {
        cmdlineP->dpiX = 300;
        cmdlineP->dpiY = 300;
    }

    cmdlineP->center  =  !nocenter;
    cmdlineP->canturn =  !noturn;
    cmdlineP->showpage = !noshowpage;

    validateCompDimension(width, 72, "-width value");
    validateCompDimension(height, 72, "-height value");
    
    cmdlineP->width  = width * 72;
    cmdlineP->height = height * 72;

    if (imagewidthSpec) {
        validateCompDimension(imagewidth, 72, "-imagewidth value");
        cmdlineP->imagewidth = imagewidth * 72;
    }
    else
        cmdlineP->imagewidth = 0;
    if (imageheightSpec) {
        validateCompDimension(imagewidth, 72, "-imageheight value");
        cmdlineP->imageheight = imageheight * 72;
    }
    else
        cmdlineP->imageheight = 0;

    if (!cmdlineP->psfilter &&
        (cmdlineP->flate || cmdlineP->ascii85))
        pm_error("You must specify -psfilter in order to specify "
                 "-flate or -ascii85");

    if (cmdlineP->bitspersampleSpec)
        validateBps_1_2_4_8_12(cmdlineP->bitspersample);

    if (argc-1 == 0) 
        cmdlineP->inputFileName = "-";
    else if (argc-1 != 1)
        pm_error("Program takes zero or one argument (filename).  You "
                 "specified %d", argc-1);
    else
        cmdlineP->inputFileName = argv[1];

    free(option_def); 
}



static bool
progIsFlateCapable(void) {

    return
#ifdef NOFLATE
        false
#else
        true
#endif
        ;
}



static const char *
basebasename(const char * const filespec) {
/*----------------------------------------------------------------------------
  Return filename up to first period
-----------------------------------------------------------------------------*/
    char const dirsep = '/';
    const char * const lastSlashPos = strrchr(filespec, dirsep);

    char * name;
    const char * filename;

    if (lastSlashPos)
        filename = lastSlashPos + 1;
    else
        filename = filespec;

    name = strdup(filename);
    if (name != NULL) {
        char * const dotPosition = strchr(name, '.');

        if (dotPosition)
            *dotPosition = '\0';
    }
    return name;
}



#define MAX_FILTER_CT 10
    /* The maximum number of filters this code is capable of applying */



static void
initPidList(pid_t * const pidList) {

    pidList[0] = (pid_t)0;  /* end of list marker */
}



static void
addToPidList(pid_t * const pidList,
             pid_t   const newPid) {

    unsigned int i;

    for (i = 0; i < MAX_FILTER_CT && pidList[i]; ++i);

    assert(i < MAX_FILTER_CT);

    pidList[i] = newPid;
    pidList[i+1] = (pid_t)0;  /* end of list marker */
}



/*===========================================================================
  The output encoder
  ===========================================================================*/
    
enum OutputType {AsciiHex, Ascii85};

typedef struct {
    enum OutputType    outputType;
    bool               compressRle;
    bool               compressFlate;
    unsigned int       runlengthRefresh;
} OutputEncoder;



static void
initOutputEncoder(OutputEncoder  * const oeP,
                  unsigned int     const icols,
                  unsigned int     const bitsPerSample,
                  bool             const rle,
                  bool             const flate,
                  bool             const ascii85,
                  bool             const psFilter) {

    unsigned int const bytesPerRow = icols / (8/bitsPerSample) +
        (icols % (8/bitsPerSample) > 0 ? 1 : 0);
        /* Size of row buffer, padded up to byte boundary.

           A more straightforward calculation would be
           (icols * bitsPerSample + 7) / 8 ,
           but this overflows when icols is large.
        */

    oeP->outputType = ascii85 ? Ascii85 : AsciiHex;

    if (rle) {
        oeP->compressRle = true;
        oeP->runlengthRefresh = psFilter ? INT_MAX : bytesPerRow;
    } else
        oeP->compressRle = false;

    if (flate) {
        assert(psFilter);
        oeP->compressFlate = true;
    } else
        oeP->compressFlate = false;

    if (ascii85) {
        assert(psFilter);
        oeP->outputType = Ascii85;
    } else
        oeP->outputType = AsciiHex;
}



typedef void FilterFn(FILE *          const ifP,
                      FILE *          const ofP,
                      OutputEncoder * const oeP);
    /* This is a function that can be run in a separate process to do
       arbitrary modifications of the raster data stream.
    */
       


#ifndef NOFLATE
static void
initZlib(z_stream * const strmP) {

    int const level = 9; /* maximum compression.  see zlib.h */

    int ret;

    /* allocate deflate state */
    strmP->zalloc = Z_NULL;
    strmP->zfree  = Z_NULL;
    strmP->opaque = Z_NULL;

    ret = deflateInit(strmP, level);
    if (ret != Z_OK)
        pm_error("Failed to initialize zlib.");
}
#endif



static FilterFn flateFilter;

static void 
flateFilter(FILE *          const ifP,
            FILE *          const ofP,
            OutputEncoder * const oeP) {

#ifndef NOFLATE

    /* This code is based on def() in zpipe.c.  zpipe is an example program
       which comes with the zlib source package.  zpipe.c is public domain and
       is available from the Zlib website: http://www.zlib.net/

       See zlib.h for details on zlib parameters Z_NULL, Z_OK, etc.
    */
    unsigned int const chunkSz = 128*1024;
        /* 128K recommended in zpipe.c.  4096 is not efficient but works. */

    int flush;
    z_stream strm;
    unsigned char * in;
    unsigned char * out;

    in  = pm_allocrow(chunkSz, 1);
    out = pm_allocrow(chunkSz, 1);

    initZlib(&strm);

    /* compress until end of file */
    do {
        strm.avail_in = fread(in, 1, chunkSz, ifP);
        if (ferror(ifP)) {
            deflateEnd(&strm);
            pm_error("Error reading from internal pipe during "
                     "flate compression.");
        }
        flush = feof(ifP) ? Z_FINISH : Z_NO_FLUSH;
        strm.next_in = in;

        /* run deflate() on input until output buffer not full, finish
           compression if we have reached end of input.
        */
        do {
            unsigned int have;
            size_t bytesWritten;

            strm.avail_out = chunkSz;
            strm.next_out = out;
            deflate(&strm, flush);
            have = chunkSz - strm.avail_out;
            bytesWritten = fwrite(out, 1, have, ofP);
            if (ferror(ofP) || bytesWritten != have) {
                deflateEnd(&strm);
                pm_error("Error writing to internal pipe during "
                         "flate compression.");
            }
        } while (strm.avail_out == 0);
        assert(strm.avail_in == 0);     /* all input is used */

        /* done when last data in file processed */
    } while (flush != Z_FINISH);

    free(in);
    free(out); 
    deflateEnd(&strm);
    fclose(ifP);
    fclose(ofP);
#else
    assert(false);    /* filter is never used */ 
#endif
}



/* Run length encoding

   In this simple run-length encoding scheme, compressed and uncompressed
   strings follow a single index byte N.  N 0-127 means the next N+1
   bytes are uncompressed; 129-255 means the next byte is to be repeated
   257-N times.

   In native (non-psfilter) mode, the run length filter must flush at
   the end of every row.  But the entire raster is sent to the run length
   filter as one continuous stream.  The run length filter learns the
   refresh interval from oeP->runlengthRefresh.
*/


static void
rlePutBuffer (unsigned int    const repeat,
              unsigned int    const count,
              unsigned int    const repeatitem,
              unsigned char * const itembuf,
              FILE *          const fP) {

    if (repeat) {
        fputc(257 - count,  fP);
        fputc(repeatitem, fP);
    } else {
        fputc(count - 1, fP);
        fwrite(itembuf, 1, count, fP);
    }
}



static FilterFn rleFilter;

static void
rleFilter (FILE *          const ifP,
           FILE *          const ofP,
           OutputEncoder * const oeP) {

    unsigned int const refresh = oeP->runlengthRefresh;

    bool eof;
    bool repeat;
    unsigned int count;
    unsigned int incount;
    unsigned int repeatcount;
    unsigned char repeatitem;
    unsigned char itembuf[128];

    repeat = true; /* initial value */
    count = 0; /* initial value */

    for (eof = false, incount = 0; !eof; ) {
        int rleitem;

        rleitem = fgetc(ifP);
        if (rleitem == EOF)
            eof = true;
        else {
            ++incount;

            if (repeat && count == 0) {
                /* Still initializing a repeat buf. */
                itembuf[count++] = repeatitem = rleitem;
            }
            else if (repeat) {
                /* Repeating - watch for end of run. */
                if (rleitem == repeatitem) {
                    /* Run continues. */
                    itembuf[count++] = rleitem;
                } else {
                    /* Run ended */
                    if (count > 2) {
                        /* Long enough to dump, so dump a repeat-mode buffer
                           and start a new one.
                        */
                        rlePutBuffer(repeat, count, repeatitem, itembuf, ofP);
                        repeat = true;
                        count = 0;
                        itembuf[count++] = repeatitem = rleitem;
                    } else {
                        /* Not long enough - convert to non-repeat mode. */
                        repeat = false;
                        itembuf[count++] = repeatitem = rleitem;
                        repeatcount = 1;
                    }
                }
            } else {
                /* Not repeating - watch for a run worth repeating. */
                if (rleitem == repeatitem) {
                    /* Possible run continues. */
                    ++repeatcount;
                    if (repeatcount > 3) {
                        /* Long enough - dump non-repeat part and start
                           repeat.
                        */
                        unsigned int i;
                        count = count - (repeatcount - 1);
                        rlePutBuffer(repeat, count, repeatitem, itembuf, ofP);
                        repeat = true;
                        count = repeatcount;
                        for (i = 0; i < count; ++i)
                            itembuf[i] = rleitem;
                    } else {
                        /* Not long enough yet - continue as non-repeat buf. */
                        itembuf[count++] = rleitem;
                    }
                } else {                    /* Broken run. */
                    itembuf[count++] = repeatitem = rleitem;
                    repeatcount = 1;
                }
            }

            if (incount == refresh) {
                rlePutBuffer(repeat, count, repeatitem, itembuf, ofP);
                repeat = true;
                count = incount = 0;
            }

            if (count == 128) {
                rlePutBuffer(repeat, count, repeatitem, itembuf, ofP);
                repeat = true;
                count = 0;
            }
        }
    }

    if (count > 0)
        rlePutBuffer(repeat, count, repeatitem, itembuf, ofP);

    fclose(ifP);
    fclose(ofP);
}



static FilterFn asciiHexFilter;

static void
asciiHexFilter(FILE *          const ifP,
               FILE *          const ofP,
               OutputEncoder * const oeP) {

    char const hexits[16] = "0123456789abcdef";

    bool eof;
    unsigned char inbuff[40], outbuff[81];

    for (eof = false; !eof; ) {
        size_t bytesRead;

        bytesRead = fread(inbuff, 1, 40, ifP);

        if (bytesRead == 0)
            eof = true;
        else {
            unsigned int i;

            for (i = 0; i < bytesRead; ++i) {
                int const item = inbuff[i]; 
                outbuff[i*2]   = hexits[item >> 4];
                outbuff[i*2+1] = hexits[item & 15];
            }
        }
        outbuff[bytesRead * 2] = '\n';
        fwrite(outbuff, 1, bytesRead*2 + 1, ofP);
    }

    fclose(ifP);
    fclose(ofP);
}



static FilterFn ascii85Filter;

static void
ascii85Filter(FILE *          const ifP,
              FILE *          const ofP,
              OutputEncoder * const oeP) {

    bool eof;
    char outbuff[5];
    unsigned long int value; /* requires 32 bits */
    int count;
    int outcount;

    value = 0;  /* initial value */
    count = 0;  /* initial value */
    outcount = 0; /* initial value */

    for (eof = false; !eof; ) {
        int c;

        c = fgetc(ifP);

        if (c == EOF)
            eof = true;
        else {
            value = value*256 + c;
            ++count;

            if (value == 0 && count == 4) {
                putchar('z');  /* Ascii85 encoding z exception */
                ++outcount;
                count = 0;
            } else if (count == 4) {
                outbuff[4] = value % 85 + 33;  value/=85; 
                outbuff[3] = value % 85 + 33;  value/=85;
                outbuff[2] = value % 85 + 33;  value/=85;
                outbuff[1] = value % 85 + 33;
                outbuff[0] = value / 85 + 33;

                fwrite(outbuff, 1, count + 1, ofP);
                count = value = 0;
                outcount += 5; 
            }

            if (outcount > 75) {
                putchar('\n');
                outcount = 0;
            }
        }
    }

    if (count > 0) { /* EOF, flush */
        assert (count < 4);

        value <<= (4 - count) * 8;   value/=85;
        outbuff[3] = value % 85 + 33;  value/=85;
        outbuff[2] = value % 85 + 33;  value/=85;
        outbuff[1] = value % 85 + 33;
        outbuff[0] = value / 85 + 33;
        outbuff[count + 1] = '\n';

        fwrite(outbuff, 1, count + 2, ofP);
    }

    fclose(ifP);
    fclose(ofP);
}



static void
makePipe(int * const pipeFdArray) {

    int rc;
    rc = pm_pipe(pipeFdArray);
    if (rc == -1)
        pm_error("pipe() failed, errno = %d (%s)", errno, strerror(errno));
}



static void
closeAllBut(int const saveFd0,
            int const saveFd1,
            int const saveFd2) {
/*----------------------------------------------------------------------------
   Close every file descriptor in this process except 'saveFd0',
   'saveFd1', and 'saveFd2'.

   This is helpful because even if this process doesn't touch other file
   desriptors, its very existence will keep the files open.
-----------------------------------------------------------------------------*/
    
    /* Unix provides no good way to do this; we just assume file descriptors
       above 9 are not used in this program; Caller must ensure that is true.
    */
    int fd;

    for (fd = 0; fd < 10; ++fd) {
        if (fd != saveFd0 && fd != saveFd1 && fd != saveFd2)
            close(fd);
    }
}



static void
spawnFilter(FILE *          const ofP,
            FilterFn *      const filterFn,
            OutputEncoder * const oeP,
            FILE **         const feedFilePP,
            pid_t *         const pidP) {
/*----------------------------------------------------------------------------
   Fork a child process to run filter function 'filterFn' and send its
   output to *ofP.

   Create a pipe for feeding the filter and return as *feedFilePP the
   stream to which Caller can write to push stuff into the filter.

   *oeP is the parameter to 'filterFn'.
-----------------------------------------------------------------------------*/
    int pipeFd[2];
    pid_t rc;

    makePipe(pipeFd);
    
    rc = fork();

    if (rc == (pid_t)-1)
        pm_error("fork() of filter process failed.  errno=%d (%s)", 
                 errno, strerror(errno));
    else if (rc == 0) {
        /* This is the child process */
 
        FILE * ifP;

        ifP = fdopen(pipeFd[0], "r");

        if (!ifP)
            pm_error("filter process failed to make "
                     "file stream (\"FILE\") "
                     "out of the file descriptor which is input to the "
                     "filter.  errno=%d (%s)",
                     errno, strerror(errno));

        closeAllBut(fileno(ifP), fileno(ofP), STDERR_FILENO);

        filterFn(ifP, ofP, oeP);

        exit(EXIT_SUCCESS);
    } else {
        /* This is the parent process */

        pid_t const childPid = rc;

        close(pipeFd[0]);

        *feedFilePP = fdopen(pipeFd[1], "w");

        *pidP = childPid;
    }
}



static void
addFilter(const char *    const description,
          FilterFn *      const filter,
          OutputEncoder * const oeP,
          FILE **         const feedFilePP,
          pid_t *         const pidList) {

    pid_t pid;

    FILE * const oldFeedFileP = *feedFilePP;

    FILE * newFeedFileP;
        
    spawnFilter(oldFeedFileP, filter, oeP, &newFeedFileP, &pid);
            
    if (verbose)
        pm_message("%s filter spawned: pid %u",
                   description, (unsigned)pid);
    
    fclose(oldFeedFileP);  /* Child keeps this open now */
    
    addToPidList(pidList, pid);

    *feedFilePP = newFeedFileP;
}



static void
spawnFilters(FILE *          const ofP,
             OutputEncoder * const oeP,
             FILE **         const feedFilePP,
             pid_t *         const pidList) {
/*----------------------------------------------------------------------------
   Get all the child processes for the filters running and connected.
   Return at *feedFileP the file stream to which to write the raw data,
   with the filtered data going to *ofP.

   Filter according to *oeP.
-----------------------------------------------------------------------------*/

    /* Build up the pipeline from the final to the initial stage.  The
       result is one of:

          FEED | convertRow | asciiHexFilter | *ofP
          FEED | convertRow | ascii85Filter | *ofP
          FEED | convertRow | rleFilter   | asciiHexFilter | *ofP
          FEED | convertRow | flateFilter | asciiHexFilter | *ofP
          FEED | convertRow | flateFilter | rleFilter | asciiHexFilter | *ofP
    */

    FILE * feedFileP;
        /* The current head of the filter chain; changes as we add filters */

    initPidList(pidList);

    feedFileP = ofP;  /* Initial state: no filter at all */

    addFilter(
        "output",
        oeP->outputType == Ascii85 ? &ascii85Filter : asciiHexFilter,
        oeP,
        &feedFileP,
        pidList);

    if (oeP->compressFlate)
        addFilter("flate", flateFilter, oeP, &feedFileP, pidList);

    if (oeP->compressRle)
        addFilter("rle", rleFilter, oeP, &feedFileP, pidList);

    *feedFilePP = feedFileP;
}



static void
waitForChildren(const pid_t * const pidList) {
/*----------------------------------------------------------------------------
   Wait for all child processes with PIDs in pidList[] to exit.
   In pidList[], end-of-list is marked with a special zero value.
-----------------------------------------------------------------------------*/
    unsigned int i;

    for (i = 0; pidList[i]; ++i) {
        pid_t rc;
        int status;

        if (verbose)
            pm_message("Waiting for PID %u to exit", (unsigned)pidList[i]);

        rc = waitpid(pidList[i], &status, 0);
        if (rc == -1)
            pm_error ("waitpid() for child %u failed", i);
        else if (status != EXIT_SUCCESS)
            pm_error ("Child process %u terminated abnormally", i);
    }
    if (verbose)
        pm_message("All children have exited");
}



/*============================================================================
  END OF OUTPUT ENCODERS
============================================================================*/



static void
validateComputableBoundingBox(float const scols, 
                              float const srows,
                              float const llx, 
                              float const lly) {

    float const bbWidth  = llx + scols + 0.5;
    float const bbHeight = lly + srows + 0.5;

    if (bbHeight < INT_MIN || bbHeight > INT_MAX ||
        bbWidth  < INT_MIN || bbWidth  > INT_MAX)
        pm_error("Bounding box dimensions %.1f x %.1f are too large "
                 "for computations.  "
                 "This probably means input image width, height, "
                 "or scale factor is too large", bbWidth, bbHeight);
}



static void
computeImagePosition(int     const dpiX, 
                     int     const dpiY, 
                     int     const icols, 
                     int     const irows,
                     bool    const mustturn,
                     bool    const canturn,
                     bool    const center,
                     int     const pagewid, 
                     int     const pagehgt, 
                     float   const requestedScale,
                     float   const imagewidth,
                     float   const imageheight,
                     bool    const equalpixels,
                     float * const scolsP,
                     float * const srowsP,
                     float * const llxP, 
                     float * const llyP,
                     bool *  const turnedP ) {
/*----------------------------------------------------------------------------
  Determine where on the page the image is to go.  This means position,
  dimensions, and orientation.

  icols/irows are the dimensions of the PNM input in xels.

  'mustturn' means we are required to rotate the image.

  'canturn' means we may rotate the image if it fits better, but don't
  have to.

  *scolsP, *srowsP are the dimensions of the image in 1/72 inch.

  *llxP, *llyP are the coordinates in the Postcript frame, of the lower left
  corner of the image on the page.  The Postscript frame is different from the
  Neptbm frame: units are 1/72 inch (1 point) and (0,0) is the lower left
  corner.

  *turnedP is true iff the image is to be rotated 90 degrees on the page.

  imagewidth/imageheight are the requested dimensions of the image on
  the page, in 1/72 inch.  Image will be as large as possible within
  those dimensions.  Zero means unspecified, so 'scale', 'pagewid',
  'pagehgt', 'irows', and 'icols' determine image size.

  'equalpixels' means the user wants one printed pixel per input pixel.
  It is inconsistent with imagewidth or imageheight != 0

  'requestedScale' is meaningful only when imageheight/imagewidth == 0
  and equalpixels == FALSE.  It tells how many inches the user wants
  72 pixels of input to occupy, if it fits on the page.
-----------------------------------------------------------------------------*/
    int cols, rows;
    /* Number of columns, rows of input xels in the output, as
       rotated if applicable
    */
    bool shouldturn;  /* The image fits the page better if we turn it */
    
    if (icols > irows && pagehgt > pagewid)
        shouldturn = TRUE;
    else if (irows > icols && pagewid > pagehgt)
        shouldturn = TRUE;
    else
        shouldturn = FALSE;

    if (mustturn || (canturn && shouldturn)) {
        *turnedP = TRUE;
        cols = irows;
        rows = icols;
    } else {
        *turnedP = FALSE;
        cols = icols;
        rows = irows;
    }
    if (equalpixels) {
        *scolsP = (72.0/dpiX)*cols;
        *srowsP = (72.0/dpiY)*rows;
    } else if (imagewidth > 0 || imageheight > 0) {
        float scale;

        if (imagewidth == 0)
            scale = (float) imageheight/rows;
        else if (imageheight == 0)
            scale = (float) imagewidth/cols;
        else
            scale = MIN((float)imagewidth/cols, (float)imageheight/rows);
    
        *scolsP = cols*scale;
        *srowsP = rows*scale;
    } else {
        /* He didn't give us a bounding box for the image so figure
           out output image size from other inputs.
        */
        const int devpixX = dpiX / 72.0 + 0.5;        
        const int devpixY = dpiY / 72.0 + 0.5;        
        /* How many device pixels make up 1/72 inch, rounded to
           nearest integer */
        const float pixfacX = 72.0 / dpiX * devpixX;  /* 1, approx. */
        const float pixfacY = 72.0 / dpiY * devpixY;  /* 1, approx. */
        float scale;

        scale = MIN(requestedScale, 
                    MIN((float)pagewid/cols, (float)pagehgt/rows));

        *scolsP = scale * cols * pixfacX;
        *srowsP = scale * rows * pixfacY;
    
        if (scale != requestedScale)
            pm_message("warning, image too large for page, rescaling to %g", 
                       scale );

        /* Before May 2001, Pnmtops enforced a 5% margin around the page.
           If the image would be too big to leave a 5% margin, Pnmtops would
           scale it down.  But people have images that are exactly the size
           of a page, e.g. because they created them with Sane's 'scanimage'
           program from a full page of input.  So we removed the gratuitous
           5% margin.  -Bryan.
        */
    }
    *llxP = (center) ? ( pagewid - *scolsP ) / 2 : 0;
    *llyP = (center) ? ( pagehgt - *srowsP ) / 2 : 0;

    validateComputableBoundingBox( *scolsP, *srowsP, *llxP, *llyP);

    if (verbose)
        pm_message("Image will be %3.2f points wide by %3.2f points high, "
                   "left edge %3.2f points from left edge of page, "
                   "bottom edge %3.2f points from bottom of page; "
                   "%sturned to landscape orientation",
                   *scolsP, *srowsP, *llxP, *llyP, *turnedP ? "" : "NOT ");
}



static void
determineDictionaryRequirement(bool           const userWantsDict,
                               bool           const psFilter,
                               unsigned int * const dictSizeP) {

    if (userWantsDict) {
        if (psFilter) {
            /* The Postscript this program generates to use built-in
               Postscript filters does not define any variables.
            */
            *dictSizeP = 0;
        } else
            *dictSizeP = 8;
    } else
        *dictSizeP = 0;
}



static void
defineReadstring(bool const rle) {
/*----------------------------------------------------------------------------
  Write to Standard Output Postscript statements to define /readstring.
-----------------------------------------------------------------------------*/
    if (rle) {
        printf("/rlestr1 1 string def\n");
        printf("/readrlestring {\n");             /* s -- nr */
        printf("  /rlestr exch def\n");           /* - */
        printf("  currentfile rlestr1 readhexstring pop\n");  /* s1 */
        printf("  0 get\n");                  /* c */
        printf("  dup 127 le {\n");               /* c */
        printf("    currentfile rlestr 0\n");         /* c f s 0 */
        printf("    4 3 roll\n");             /* f s 0 c */
        printf("    1 add  getinterval\n");           /* f s */
        printf("    readhexstring pop\n");            /* s */
        printf("    length\n");               /* nr */
        printf("  } {\n");                    /* c */
        printf("    257 exch sub dup\n");         /* n n */
        printf("    currentfile rlestr1 readhexstring pop\n");/* n n s1 */
        printf("    0 get\n");                /* n n c */
        printf("    exch 0 exch 1 exch 1 sub {\n");       /* n c 0 1 n-1*/
        printf("      rlestr exch 2 index put\n");
        printf("    } for\n");                /* n c */
        printf("    pop\n");                  /* nr */
        printf("  } ifelse\n");               /* nr */
        printf("} bind def\n");
        printf("/readstring {\n");                /* s -- s */
        printf("  dup length 0 {\n");             /* s l 0 */
        printf("    3 copy exch\n");              /* s l n s n l*/
        printf("    1 index sub\n");              /* s l n s n r*/
        printf("    getinterval\n");              /* s l n ss */
        printf("    readrlestring\n");            /* s l n nr */
        printf("    add\n");                  /* s l n */
        printf("    2 copy le { exit } if\n");        /* s l n */
        printf("  } loop\n");                 /* s l l */
        printf("  pop pop\n");                /* s */
        printf("} bind def\n");
    } else {
        printf("/readstring {\n");                /* s -- s */
        printf("  currentfile exch readhexstring pop\n");
        printf("} bind def\n");
    }
}



static void
setupReadstringNative(bool         const rle,
                      bool         const color,
                      unsigned int const icols, 
                      unsigned int const bitsPerSample) {
/*----------------------------------------------------------------------------
  Write to Standard Output statements to define /readstring and also
  arguments for it (/picstr or /rpicstr, /gpicstr, and /bpicstr).
-----------------------------------------------------------------------------*/
    unsigned int const bytesPerRow = icols / (8/bitsPerSample) +
        (icols % (8/bitsPerSample) > 0 ? 1 : 0);
        /* Size of row buffer, padded up to byte boundary. */

    defineReadstring(rle);
    
    if (color) {
        printf("/rpicstr %d string def\n", bytesPerRow);
        printf("/gpicstr %d string def\n", bytesPerRow);
        printf("/bpicstr %d string def\n", bytesPerRow);
    } else
        printf("/picstr %d string def\n", bytesPerRow);
}



static void
putFilters(unsigned int const postscriptLevel,
           bool         const rle,
           bool         const flate,
           bool         const ascii85,
           bool         const color) {

    assert(postscriptLevel > 1);
    
    /* We say to decode flate, then rle, so Caller must ensure it encodes
       rel, then flate.
    */

    if (ascii85)
        printf("/ASCII85Decode filter ");
    else 
        printf("/ASCIIHexDecode filter ");
    if (flate)
        printf("/FlateDecode filter ");
    if (rle) 
        printf("/RunLengthDecode filter ");
}



static void
putReadstringNative(bool const color) {

    if (color) {
        printf("{ rpicstr readstring }\n");
        printf("{ gpicstr readstring }\n");
        printf("{ bpicstr readstring }\n");
    } else
        printf("{ picstr readstring }\n");
}



static void
putSetup(unsigned int const dictSize,
         bool         const psFilter,
         bool         const rle,
         bool         const color,
         unsigned int const icols,
         unsigned int const bitsPerSample) {
/*----------------------------------------------------------------------------
  Put the setup section in the Postscript program on Standard Output.
-----------------------------------------------------------------------------*/
    printf("%%%%BeginSetup\n");

    if (dictSize > 0)
        /* inputf {r,g,b,}pictsr readstring readrlestring rlestring */
        printf("%u dict begin\n", dictSize);
    
    if (!psFilter)
        setupReadstringNative(rle, color, icols, bitsPerSample);

    printf("%%%%EndSetup\n");
}



static void
putImage(bool const psFilter,
         bool const color) {
/*----------------------------------------------------------------------------
  Put the image/colorimage statement in the Postscript program on
  Standard Output.
-----------------------------------------------------------------------------*/
    if (color) {
        if (psFilter)
            printf("false 3\n");
        else
            printf("true 3\n");
        printf("colorimage");
    } else
        printf("image");
}



static void
putInitPsFilter(unsigned int const postscriptLevel,
                bool         const rle,
                bool         const flate,
                bool         const ascii85,
                bool         const color) {

    bool const filterTrue = TRUE;

    printf("{ currentfile ");

    putFilters(postscriptLevel, rle, flate, ascii85, color);

    putImage(filterTrue, color);
    
    printf(" } exec");
}



static void
putInitReadstringNative(bool const color) {

    bool const filterFalse = FALSE;

    putReadstringNative(color);
    
    putImage(filterFalse, color);
}



static void
putInit(unsigned int const postscriptLevel,
        char         const name[], 
        int          const icols, 
        int          const irows, 
        float        const scols, 
        float        const srows,
        float        const llx, 
        float        const lly,
        int          const bitsPerSample,
        int          const pagewid, 
        int          const pagehgt,
        bool         const color, 
        bool         const turned, 
        bool         const rle,
        bool         const flate,
        bool         const ascii85,
        bool         const setpage,
        bool         const psFilter,
        unsigned int const dictSize) {
/*----------------------------------------------------------------------------
  Write out to Standard Output the headers stuff for the Postscript
  program (everything up to the raster).
-----------------------------------------------------------------------------*/
    /* The numbers in the %! line often confuse people. They are NOT the
       PostScript language level.  The first is the level of the DSC comment
       spec being adhered to, the second is the level of the EPSF spec being
       adhered to.  It is *incorrect* to claim EPSF compliance if the file
       contains a setpagedevice.
    */
    printf("%%!PS-Adobe-3.0%s\n", setpage ? "" : " EPSF-3.0");
    printf("%%%%LanguageLevel: %u\n", postscriptLevel);
    printf("%%%%Creator: pnmtops\n");
    printf("%%%%Title: %s.ps\n", name);
    printf("%%%%Pages: 1\n");
    printf(
        "%%%%BoundingBox: %d %d %d %d\n",
        (int) llx, (int) lly,
        (int) (llx + scols + 0.5), (int) (lly + srows + 0.5));
    printf("%%%%EndComments\n");

    putSetup(dictSize, psFilter, rle, color, icols, bitsPerSample);

    printf("%%%%Page: 1 1\n");
    if (setpage)
        printf("<< /PageSize [ %d %d ] /ImagingBBox null >> setpagedevice\n",
               pagewid, pagehgt);
    printf("gsave\n");
    printf("%g %g translate\n", llx, lly);
    printf("%g %g scale\n", scols, srows);
    if (turned)
        printf("0.5 0.5 translate  90 rotate  -0.5 -0.5 translate\n");
    printf("%d %d %d\n", icols, irows, bitsPerSample);
    printf("[ %d 0 0 -%d 0 %d ]\n", icols, irows, irows);

    if (psFilter)
        putInitPsFilter(postscriptLevel, rle, flate, ascii85, color);
    else
        putInitReadstringNative(color);

    printf("\n");
    fflush(stdout);
}



static void
putEnd(bool         const showpage, 
       bool         const psFilter,
       bool         const ascii85,
       unsigned int const dictSize,
       bool         const vmreclaim) {

    if (psFilter) {
        if (ascii85)
            printf("%s\n", "~>");
        else
            printf("%s\n", ">");
    } else {
        printf("currentdict /inputf undef\n");
        printf("currentdict /picstr undef\n");
        printf("currentdict /rpicstr undef\n");
        printf("currentdict /gpicstr undef\n");
        printf("currentdict /bpicstr undef\n");
    }

    if (dictSize > 0)
        printf("end\n");

    if (vmreclaim)
        printf("1 vmreclaim\n");

    printf("grestore\n");

    if (showpage)
        printf("showpage\n");
    printf("%%%%Trailer\n");
}



static void
validateBpsRequest(unsigned int const bitsPerSampleReq,
                   unsigned int const postscriptLevel,
                   bool         const psFilter) {

    if (postscriptLevel < 2 && bitsPerSampleReq > 8)
        pm_error("You requested %u bits per sample, but in Postscript "
                 "level 1, 8 is the maximum.  You can get 12 with "
                 "-level 2 and -psfilter", bitsPerSampleReq);
    else if (!psFilter && bitsPerSampleReq > 8)
        pm_error("You requested %u bits per sample, but without "
                 "-psfilter, the maximum is 8", bitsPerSampleReq);
}

    

static unsigned int
bpsFromInput(unsigned int const bitsRequiredByMaxval,
             unsigned int const postscriptLevel,
             bool         const psFilter) {

    unsigned int retval;

    if (bitsRequiredByMaxval <= 1)
        retval = 1;
    else if (bitsRequiredByMaxval <= 2)
        retval = 2;
    else if (bitsRequiredByMaxval <= 4)
        retval = 4;
    else if (bitsRequiredByMaxval <= 8)
        retval = 8;
    else {
        /* Post script level 2 defines a format with 12 bits per sample,
           but I don't know the details of that format (both RLE and
           non-RLE variations) and existing native raster generation code
           simply can't handle bps > 8.  But the built-in filters know
           how to do 12 bps.
        */
        if (postscriptLevel >= 2 && psFilter)
            retval = 12;
        else
            retval = 8;
    }
    return retval;
}



static void
warnUserAboutReducedDepth(unsigned int const bitsGot,
                          unsigned int const bitsWanted,
                          bool         const userRequested,
                          unsigned int const postscriptLevel,
                          bool         const psFilter) {

    if (bitsGot < bitsWanted) {
        pm_message("Postscript will have %u bits of color resolution, "
                   "though the input has %u bits.",
                   bitsGot, bitsWanted);

        if (!userRequested) {
            if (postscriptLevel < 2)
                pm_message("Postscript level %u has a maximum depth of "
                           "8 bits.  "
                           "You could get up to 12 with -level=2 "
                           "and -psfilter.",
                           postscriptLevel);
            else {
                if (!psFilter)
                    pm_message("You can get up to 12 bits with -psfilter");
                else
                    pm_message("The Postscript maximum is 12.");
            }
        }
    }
}



static void
computeDepth(xelval         const inputMaxval,
             unsigned int   const postscriptLevel, 
             bool           const psFilter,
             unsigned int   const bitsPerSampleReq,
             unsigned int * const bitsPerSampleP) {
/*----------------------------------------------------------------------------
  Figure out how many bits will represent each sample in the Postscript
  program, and the maxval of the Postscript program samples.  The maxval
  is just the maximum value allowable in the number of bits.

  'bitsPerSampleReq' is the bits per sample that the user requests, or
  zero if he made no request.
-----------------------------------------------------------------------------*/
    unsigned int const bitsRequiredByMaxval = pm_maxvaltobits(inputMaxval);

    if (bitsPerSampleReq != 0) {
        validateBpsRequest(bitsPerSampleReq, postscriptLevel, psFilter);
        *bitsPerSampleP = bitsPerSampleReq;
    } else {
        *bitsPerSampleP = bpsFromInput(bitsRequiredByMaxval,
                                       postscriptLevel, psFilter);
    }
    warnUserAboutReducedDepth(*bitsPerSampleP, bitsRequiredByMaxval,
                              bitsPerSampleReq != 0,
                              postscriptLevel, psFilter);

    if (verbose) {
        unsigned int const psMaxval = pm_bitstomaxval(*bitsPerSampleP);
        pm_message("Input maxval is %u.  Postscript raster will have "
                   "%u bits per sample, so maxval = %u",
                   inputMaxval, *bitsPerSampleP, psMaxval);
    }
}    



/*===========================================================================
  The bit accumulator
===========================================================================*/

typedef struct {
    unsigned int value;
    unsigned int consumed;
} BitAccumulator;



static void
ba_init(BitAccumulator * const baP) {

    baP->value    = 0;
    baP->consumed = 0;
}



static void
ba_add12(BitAccumulator * const baP,
         unsigned int     const new12,
         FILE           * const fP) {
/*----------------------------------------------------------------------------
  Read a 12-bit string into the bit accumulator baP->value.
  On every other call, combine two 12-bit strings and write out three bytes.
-----------------------------------------------------------------------------*/
    assert (baP->consumed == 12 || baP->consumed == 0);

    if (baP->consumed == 12){
        char const oldHi8 = (baP->value) >> 4;
        char const oldLo4 = (baP->value) & 0x0f;
        char const newHi4 = new12 >> 8;
        char const newLo8 = new12 & 0xff;

        fputc(oldHi8, fP);
        fputc((oldLo4 << 4) | newHi4 , fP);
        fputc(newLo8, fP);
        baP->value = 0; baP->consumed = 0;
    } else {
        baP->value = new12;  baP->consumed = 12;
    }
}



static void
ba_add(BitAccumulator * const baP,
       unsigned int     const b,
       unsigned int     const bitsPerSample,
       FILE           * const fP) {
/*----------------------------------------------------------------------------
  Combine bit sequences that do not fit into a byte.

  Used when bitsPerSample =1, 2, 4.  
  Logic also works for bitsPerSample = 8, 16.

  The accumulator, baP->value is unsigned int (usually 32 bits), but
  only 8 bits are used.
-----------------------------------------------------------------------------*/
    unsigned int const bufSize = 8;

    assert (bitsPerSample == 1 || bitsPerSample == 2 || bitsPerSample == 4);

    baP->value = (baP->value << bitsPerSample) | b ;
    baP->consumed += bitsPerSample;
    if (baP->consumed == bufSize) {
        /* flush */
        fputc( baP->value, fP);
        baP->value = 0;
        baP->consumed = 0;
    }
}



static void
ba_flush(BitAccumulator * const baP,
         FILE *           const fP) {
/*----------------------------------------------------------------------------
  Flush partial bits in baP->consumed.
-----------------------------------------------------------------------------*/
    if (baP->consumed == 12) {
        char const oldHi8 = (baP->value) >> 4;
        char const oldLo4 = (baP->value) & 0x0f;
        fputc(oldHi8, fP);
        fputc(oldLo4 << 4, fP);
    } else if (baP->consumed == 8)
        fputc(baP->value , fP);
    else if (baP->consumed > 0) {
        unsigned int const leftShift = 8 - baP->consumed;
        assert(baP->consumed <= 8);  /* why? */
        baP->value <<= leftShift;
        fputc(baP->value , fP);
    }
    baP->value = 0;
    baP->consumed = 0;
}



static void
outputSample(BitAccumulator * const baP,
             unsigned int     const sampleValue,
             unsigned int     const bitsPerSample,
             FILE           * const fP) {

    if (bitsPerSample == 8)
        fputc(sampleValue, fP);
    else if (bitsPerSample == 12)
        ba_add12(baP, sampleValue, fP);
    else
        ba_add(baP, sampleValue, bitsPerSample, fP);
}



static void
flushOutput(BitAccumulator * const baP,
            FILE *           const fP) {
    ba_flush(baP, fP);
}



/*----------------------------------------------------------------------
  Row converters

  convertRowPbm is a fast routine for PBM images.
  It is used only when the input is PBM and the user does not specify
  a -bitspersample value greater than 1.  It is not used when the input
  image is PGM or PPM and the output resolution is brought down to one
  bit per pixel by -bitpersample=1 .

  convertRowNative and convertRowPsFilter are the general converters.
  They are quite similar, the differences being:
  (1) Native output separates the color planes: 
  (RRR...RRR GGG...GGG BBB...BBB),
  whereas psFilter does not:
  (RGB RGB RGB RGB ......... RGB).
  (2) Native flushes the run-length encoder at the end of each row if
  grayscale, at the end of each plane if color.

  Both convertRowNative and convertRowPsFilter can handle PBM, though we
  don't use them.

  If studying the code, read convertRowPbm first.  convertRowNative and
  convertRowPsFilter are constructs that pack raster data into a form
  similar to a binary PBM bitrow.
  ----------------------------------------------------------------------*/

static void
convertRowPbm(struct pam *     const pamP,
              unsigned char  * const bitrow,
              bool             const psFilter,
              FILE *           const fP) {
/*---------------------------------------------------------------------
  Feed PBM raster data directly to the output encoder.
  Invert bits: 0 is "white" in PBM, 0 is "black" in postscript.
----------------------------------------------------------------------*/
    unsigned int colChar;
    unsigned int const colChars = pbm_packed_bytes(pamP->width);
    unsigned int const padRight = (8 - pamP->width %8) %8;

    pbm_readpbmrow_packed(pamP->file, bitrow, pamP->width, pamP->format);

    for (colChar = 0; colChar < colChars; ++colChar)
        bitrow[colChar] =  ~ bitrow[colChar];

    if (padRight > 0) {
        bitrow[colChars-1] >>= padRight;  /* Zero clear padding beyond */
        bitrow[colChars-1] <<= padRight;  /* right edge */
    }

    fwrite(bitrow, 1, colChars, fP); 
}



static void
convertRowNative(struct pam *     const pamP, 
                 tuple *                tuplerow, 
                 unsigned int     const bitsPerSample,
                 FILE           * const fP) { 

    unsigned int const psMaxval = pm_bitstomaxval(bitsPerSample);

    unsigned int plane;
    BitAccumulator ba;

    ba_init(&ba);

    pnm_readpamrow(pamP, tuplerow);
    pnm_scaletuplerow(pamP, tuplerow, tuplerow, psMaxval);

    for (plane = 0; plane < pamP->depth; ++plane) {
        unsigned int col;
        for (col= 0; col < pamP->width; ++col)
            outputSample(&ba, tuplerow[col][plane], bitsPerSample, fP);

        flushOutput(&ba, fP);
    }
}



static void
convertRowPsFilter(struct pam *     const pamP,
                   tuple *                tuplerow,
                   unsigned int     const bitsPerSample,
                   FILE           * const fP) { 

    unsigned int const psMaxval = pm_bitstomaxval(bitsPerSample);

    unsigned int col;
    BitAccumulator ba;

    ba_init(&ba);

    pnm_readpamrow(pamP, tuplerow);
    pnm_scaletuplerow(pamP, tuplerow, tuplerow, psMaxval);

    for (col = 0; col < pamP->width; ++col) {
        unsigned int plane;
        for (plane = 0; plane < pamP->depth; ++plane)
            outputSample(&ba, tuplerow[col][plane], bitsPerSample, fP);
    }
    flushOutput(&ba, fP);

}



static void
selectPostscriptLevel(bool           const levelIsGiven,
                      unsigned int   const levelGiven,
                      bool           const color,
                      bool           const dict,
                      bool           const flate,
                      bool           const ascii85,
                      bool           const psFilter,
                      unsigned int * const postscriptLevelP) {

    unsigned int const maxPermittedLevel = 
        levelIsGiven ? levelGiven : UINT_MAX;
    unsigned int minPossibleLevel;

    /* Until we know, later in this function, that we needs certain
       features, we assume we can get by with classic Postscript Level 1:
    */
    minPossibleLevel = 1;

    /* Now we increase 'minPossibleLevel' as we notice that each of
       various features are required:
    */
    if (color) {
        minPossibleLevel = MAX(minPossibleLevel, 2);
        if (2 > maxPermittedLevel)
            pm_error("Color requires at least Postscript level 2");
    }
    if (flate) {
        minPossibleLevel = MAX(minPossibleLevel, 3);
        if (2 > maxPermittedLevel)
            pm_error("flate compression requires at least Postscript level 3");
    }
    if (ascii85) {
        minPossibleLevel = MAX(minPossibleLevel, 2);
        if (2 > maxPermittedLevel)
            pm_error("ascii85 encoding requires at least Postscript level 2");
    }
    if (psFilter) {
        minPossibleLevel = MAX(minPossibleLevel, 2);
        if (2 > maxPermittedLevel)
            pm_error("-psfilter requires at least Postscript level 2");
    }
    if (levelIsGiven)
        *postscriptLevelP = levelGiven;
    else
        *postscriptLevelP = minPossibleLevel;
}



static void
convertRaster(struct pam * const inpamP,
              unsigned int const bitsPerSample,
              bool         const psFilter,
              FILE *       const fP) {

    if (PAM_FORMAT_TYPE(inpamP->format) == PBM_TYPE && bitsPerSample == 1)  {
        unsigned char * bitrow;
        unsigned int row;

        bitrow = pbm_allocrow_packed(inpamP->width);

        for (row = 0; row < inpamP->height; ++row)
            convertRowPbm(inpamP, bitrow, psFilter, fP);

        pbm_freerow(bitrow);
    } else  {
        tuple *tuplerow;
        unsigned int row;
        
        tuplerow = pnm_allocpamrow(inpamP);

        for (row = 0; row < inpamP->height; ++row) {
            if (psFilter)
                convertRowPsFilter(inpamP, tuplerow, bitsPerSample, fP);
            else
                convertRowNative(inpamP, tuplerow, bitsPerSample, fP);
        }
        pnm_freepamrow(tuplerow);
    }
}



static void
convertPage(FILE *       const ifP, 
            int          const turnflag, 
            int          const turnokflag, 
            bool         const psFilter,
            bool         const rle, 
            bool         const flate,
            bool         const ascii85,
            bool         const setpage,
            bool         const showpage,
            bool         const center, 
            float        const scale,
            int          const dpiX, 
            int          const dpiY, 
            int          const pagewid, 
            int          const pagehgt,
            int          const imagewidth, 
            int          const imageheight, 
            bool         const equalpixels,
            unsigned int const bitsPerSampleReq,
            char         const name[],
            bool         const dict,
            bool         const vmreclaim,
            bool         const levelIsGiven,
            bool         const levelGiven) {
    
    struct pam inpam;
    float scols, srows;
    float llx, lly;
    bool turned;
    bool color;
    unsigned int postscriptLevel;
    unsigned int bitsPerSample;
    unsigned int dictSize;  
        /* Size of Postscript dictionary we should define */
    OutputEncoder oe;
    pid_t filterPidList[MAX_FILTER_CT + 1];

    FILE * feedFileP;
        /* The file stream which is the head of the filter chain; we write to
           this and filtered stuff comes out the other end.
        */

    pnm_readpaminit(ifP, &inpam, PAM_STRUCT_SIZE(tuple_type));

    validateCompDimension(inpam.width, 16, "Input image width");
    
    if (!STRSEQ(inpam.tuple_type, PAM_PBM_TUPLETYPE) &&
        !STRSEQ(inpam.tuple_type, PAM_PGM_TUPLETYPE) &&
        !STRSEQ(inpam.tuple_type, PAM_PPM_TUPLETYPE))
        pm_error("Unrecognized tuple type %s.  This program accepts only "
                 "PBM, PGM, PPM, and equivalent PAM input images", 
                 inpam.tuple_type);

    color = STRSEQ(inpam.tuple_type, PAM_PPM_TUPLETYPE);
    
    selectPostscriptLevel(levelIsGiven, levelGiven, color, 
                          dict, flate, ascii85, psFilter, &postscriptLevel);
    
    if (color)
        pm_message("generating color Postscript program.");

    computeDepth(inpam.maxval, postscriptLevel, psFilter, bitsPerSampleReq,
                 &bitsPerSample);

    /* In positioning/scaling the image, we treat the input image as if
       it has a density of 72 pixels per inch.
    */
    computeImagePosition(dpiX, dpiY, inpam.width, inpam.height, 
                         turnflag, turnokflag, center,
                         pagewid, pagehgt, scale, imagewidth, imageheight,
                         equalpixels,
                         &scols, &srows, &llx, &lly, &turned);

    determineDictionaryRequirement(dict, psFilter, &dictSize);
    
    putInit(postscriptLevel, name, inpam.width, inpam.height, 
            scols, srows, llx, lly, bitsPerSample, 
            pagewid, pagehgt, color,
            turned, rle, flate, ascii85, setpage, psFilter, dictSize);

    initOutputEncoder(&oe, inpam.width, bitsPerSample,
                      rle, flate, ascii85, psFilter);

    spawnFilters(stdout, &oe, &feedFileP, filterPidList);
 
    convertRaster(&inpam, bitsPerSample, psFilter, feedFileP);

    fflush(feedFileP);
    fclose(feedFileP);

    waitForChildren(filterPidList);

    putEnd(showpage, psFilter, ascii85, dictSize, vmreclaim);
}



int
main(int argc, const char * argv[]) {

    FILE * ifP;
    const char * name;  /* malloc'ed */
    struct cmdlineInfo cmdline;

    pm_proginit(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    verbose = cmdline.verbose;

    if (cmdline.flate && !progIsFlateCapable())
        pm_error("This program cannot do flate compression.  "
                 "(There are other versions of the program that do, "
                 "though -- it's a build-time option");

    ifP = pm_openr(cmdline.inputFileName);

    if (streq(cmdline.inputFileName, "-"))
        name = strdup("noname");
    else
        name = basebasename(cmdline.inputFileName);
    {
        int eof;  /* There are no more images in the input file */
        unsigned int imageSeq;

        /* I don't know if this works at all for multi-image PNM input.
           Before July 2000, it ignored everything after the first image,
           so this probably is at least as good -- it should be identical
           for a single-image file, which is the only kind which was legal
           before July 2000.

           Maybe there needs to be some per-file header and trailers stuff
           in the Postscript program, with some per-page header and trailer
           stuff inside.  I don't know Postscript.  - Bryan 2000.06.19.
        */

        eof = FALSE;  /* There is always at least one image */
        for (imageSeq = 0; !eof; ++imageSeq) {
            convertPage(ifP, cmdline.mustturn, cmdline.canturn, 
                        cmdline.psfilter,
                        cmdline.rle, cmdline.flate, cmdline.ascii85, 
                        cmdline.setpage, cmdline.showpage,
                        cmdline.center, cmdline.scale,
                        cmdline.dpiX, cmdline.dpiY,
                        cmdline.width, cmdline.height, 
                        cmdline.imagewidth, cmdline.imageheight, 
                        cmdline.equalpixels,
                        cmdline.bitspersampleSpec ? cmdline.bitspersample : 0,
                        name, 
                        cmdline.dict, cmdline.vmreclaim,
                        cmdline.levelSpec, cmdline.level);
            pnm_nextimage(ifP, &eof);
        }
    }
    pm_strfree(name);

    pm_close(ifP);

    return 0;
}



/*
** Copyright (C) 1989 by Jef Poskanzer.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation.  This software is provided "as is" without express or
** implied warranty.
**
**
** -nocenter option added November 1993 by Wolfgang Stuerzlinger,
**  wrzl@gup.uni-linz.ac.at.
**
** July 2011 afu
** row convertors rewritten, fast PBM-only row convertor added,
** rle compression slightly modified, flate compression added
** ascii85 output end added.
**
*/