about summary refs log tree commit diff
path: root/converter/ppm/ilbmtoppm.c
blob: a1aae7f4ab308bf4884e9dabc3f29372d04ccf0b (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
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
/* ilbmtoppm.c - read an IFF ILBM file and produce a PPM
**
** 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.
**
** Modified by Mark Thompson on 10/4/90 to accomodate 24-bit IFF files
** as used by ASDG, NewTek, etc.
**
** Modified by Ingo Wilken (Ingo.Wilken@informatik.uni-oldenburg.de)
**  20/Jun/93:
**  - row-by-row operation
**  - better de-interleave algorithm
**  - colormap files
**  - direct color
**  04/Oct/93:
**  - multipalette capability (PCHG chunk)
**  - options -ignore, -isham, -isehb and -adjustcolors
**  22/May/94:
**  - minor change: check first for 24 planes, then for HAM
**  21/Sep/94:
**  - write mask plane to a file if -maskfile option used
**  - write colormap file
**  - added sliced HAM/dynamic HAM/dynamic Hires multipalette formats (SHAM, CTBL chunk)
**  - added color lookup tables (CLUT chunk)
**  - major rework of colormap/multipalette handling
**  - now uses numeric IFF IDs
**  24/Oct/94:
**  - transparentColor capability
**  - added RGBN/RGB8 image types
**  - 24-bit & direct color modified to n-bit deep ILBM
**  22/Feb/95:
**  - direct color (DCOL) reimplemented
**  29/Mar/95
**  - added IFF-PBM format
*/

#include <string.h>

#include "pm_c_util.h"
#include "mallocvar.h"
#include "intcode.h"
#include "ilbm.h"
#include "ppm.h"

typedef struct {
    int reg;            /* color register to change */
    pixval r, g, b;     /* new colors for register */
} PaletteChange;

typedef struct {
    pixel *color;
    int    ncolors;
    /* lookup tables */
    unsigned char *redlut;
    unsigned char *greenlut;
    unsigned char *bluelut;
    unsigned char *monolut;
    /* multipalette stuff */
    PaletteChange *mp_init;
    PaletteChange **mp_change;
    int mp_rows;                /* # of rows in change array */
    int mp_type;                /* see below, higher types preferred */
    int mp_flags;
    IFF_ID  mp_id;
} ColorMap;

#define HAS_COLORMAP(cmap)      ((cmap) && (cmap)->color)
#define HAS_COLORLUT(cmap)      ((cmap) && ((cmap)->redlut || (cmap)->greenlut || (cmap)->bluelut))
#define HAS_MONOLUT(cmap)       ((cmap) && (cmap)->monolut)
#define HAS_MULTIPALETTE(cmap)  (HAS_COLORMAP(cmap) && (cmap)->mp_type)
#define MP_TYPE_SHAM        1
#define MP_TYPE_CTBL        2
#define MP_TYPE_PCHG        3
#define MP_REG_IGNORE       -1
#define MP_REG_END          -2
#define MP_FLAGS_SKIPLACED   (1<<0)

#define FACTOR_4BIT     17      /* scale factor maxval 15 -> maxval 255 */

static short verbose = 0;
static short adjustcolors = 0;
static unsigned char *ilbmrow;
static pixel *pixelrow;
static FILE *maskfile = NULL;
static bit *maskrow = NULL;
static short wrotemask = 0;
static IFF_ID typeid;       /* ID_ILBM, ID_RGBN, ID_RGB8 */

static char *transpName = NULL;  /* -transparent option value */

static bool debug = FALSE;



static char *
ID2string(id)
    IFF_ID id;
{
    static char str[] = "abcd";

    str[0] = (char)(id >> 24 & 0xff);
    str[1] = (char)(id >> 16 & 0xff);
    str[2] = (char)(id >>  8 & 0xff);
    str[3] = (char)(id >>  0 & 0xff);

    return str;
}


/****************************************************************************
 Memory allocation
 ****************************************************************************/
static ColorMap *
alloc_cmap(void) {

    ColorMap * cmap;

    MALLOCVAR_NOFAIL(cmap);

    cmap->color     = NULL;
    cmap->ncolors   = 0;
    cmap->monolut   = NULL;
    cmap->redlut    = NULL;
    cmap->greenlut  = NULL;
    cmap->bluelut   = NULL;
    cmap->mp_init   = NULL;
    cmap->mp_change = NULL;
    cmap->mp_rows   = 0;
    cmap->mp_type   = 0;
    cmap->mp_flags  = 0;

    return cmap;
}



static rawtype *
alloc_rawrow(cols)
    int cols;
{
    rawtype *r;
    int i;

    MALLOCARRAY_NOFAIL(r, cols);

    for( i = 0; i < cols; i++ )
        r[i] = 0;

    return r;
}


/****************************************************************************
 Basic I/O functions
 ****************************************************************************/

static void
readerr(f, iffid)
    FILE *f;
    IFF_ID iffid;
{
    if( ferror(f) )
        pm_error("read error");
    else
        pm_error("premature EOF in %s chunk", ID2string(iffid));
}


static void
read_bytes(FILE *          const ifP,
           int             const bytes,
           unsigned char * const buffer,
           IFF_ID          const iffid,
           unsigned long * const counterP) {

    if (counterP) {
        if (*counterP < bytes)
            pm_error("insufficient data in %s chunk", ID2string(iffid));
        *counterP -= bytes;
    }
    if (fread(buffer, 1, bytes, ifP) != bytes)
        readerr(ifP, iffid);
}



static unsigned char
get_byte(ifp, iffid, counter)
    FILE* ifp;
    IFF_ID iffid;
    long *counter;
{
    int i;

    if( counter ) {
        if( *counter == 0 )
            pm_error("insufficient data in %s chunk", ID2string(iffid));
        --(*counter);
    }
    i = getc(ifp);
    if( i == EOF )
        readerr(ifp, iffid);

    return (unsigned char) i;
}

static long
get_big_long(FILE *          const ifP,
             IFF_ID          const iffid,
             unsigned long * const counterP) {

    long l;
    
    if (counterP) {
        if (*counterP < 4)
            pm_error("insufficient data in %s chunk", ID2string(iffid));
        *counterP -= 4;
    }
    if (pm_readbiglong(ifP, &l) == -1)
        readerr(ifP, iffid);

    return l;
}



static short
get_big_short(FILE *          const ifP,
              IFF_ID          const iffid,
              unsigned long * const counterP) {

    short s;

    if (counterP) {
        if (*counterP < 2)
            pm_error("insufficient data in %s chunk", ID2string(iffid));
        *counterP -= 2;
    }
    if (pm_readbigshort(ifP, &s) == -1)
        readerr(ifP, iffid);

    return s;
}



/****************************************************************************
 Chunk reader
 ****************************************************************************/

static void
chunk_end(FILE *        const ifP,
          IFF_ID        const iffid,
          unsigned long const chunksize) {

    if (chunksize > 0) {
        unsigned long remainingChunksize;
        pm_message("warning - %ld extraneous byte%s in %s chunk",
                    chunksize, (chunksize == 1 ? "" : "s"), ID2string(iffid));
        remainingChunksize = chunksize;  /* initial value */
        while (remainingChunksize > 0)
            get_byte(ifP, iffid, &remainingChunksize);
    }
}



static void
skip_chunk(FILE *        const ifP,
           IFF_ID        const iffid,
           unsigned long const chunksize) {
    unsigned long remainingChunksize;

    remainingChunksize = chunksize;  /* initial value */

    while (remainingChunksize > 0)
        get_byte(ifP, iffid, &remainingChunksize);
}



static void
display_chunk(FILE *        const ifP,
              IFF_ID        const iffid,
              unsigned long const chunksize) {

    int byte;
    unsigned long remainingChunksize;

    pm_message("contents of %s chunk:", ID2string(iffid));

    remainingChunksize = chunksize;  /* initial value */
    byte = '\0';

    while (remainingChunksize > 0) {
        byte = get_byte(ifP, iffid, &remainingChunksize);
        if (fputc(byte, stderr) == EOF)
            pm_error("write error");
    }
    if (byte != '\n')
        if (fputc('\n', stderr) == EOF)
            pm_error("write error");
}


static void
read_cmap(FILE *     const ifp,
          IFF_ID     const iffid,
          long       const chunksize,
          ColorMap * const cmap) {

    long colors;

    colors = chunksize / 3;
    if( colors == 0 ) {
        pm_error("warning - empty %s colormap", ID2string(iffid));
        skip_chunk(ifp, iffid, chunksize);
    } else {
        unsigned int i;
        if( cmap->color )               /* prefer CMAP-chunk over CMYK-chunk */
            ppm_freerow(cmap->color);
        cmap->color = ppm_allocrow(colors);
        cmap->ncolors = colors;
        
        for( i = 0; i < colors; ++i ) {
            int r, g, b;
            r = get_byte(ifp, iffid, &chunksize);
            g = get_byte(ifp, iffid, &chunksize);
            b = get_byte(ifp, iffid, &chunksize);
            PPM_ASSIGN(cmap->color[i], r, g, b);
        }
        chunk_end(ifp, iffid, chunksize);
    }
}



static void
read_cmyk(FILE *     const ifp,
          IFF_ID     const iffid,
          long       const chunksize,
          ColorMap * const cmap) {

    if( HAS_COLORMAP(cmap) ) {      /* prefer RGB color map */
        skip_chunk(ifp, iffid, chunksize);
    } else {
        long const colors = chunksize/4;
        if( colors == 0 ) {
            pm_error("warning - empty %s colormap", ID2string(iffid));
            skip_chunk(ifp, iffid, chunksize);
        } else {
            unsigned int i;
            cmap->color = ppm_allocrow(colors);
            cmap->ncolors = colors;
            
            for( i = 0; i < colors; ++i ) {
                int c, m, y, k;
                c = get_byte(ifp, iffid, &chunksize);
                m = get_byte(ifp, iffid, &chunksize);
                y = get_byte(ifp, iffid, &chunksize);
                k = get_byte(ifp, iffid, &chunksize);

                {
                    pixval const red = 
                        MAXCOLVAL - MIN(MAXCOLVAL,
                                        c*(MAXCOLVAL-k)/MAXCOLVAL+k); 
                    pixval const green = 
                        MAXCOLVAL - MIN(MAXCOLVAL,
                                        m*(MAXCOLVAL-k)/MAXCOLVAL+k);
                    pixval const blue = 
                        MAXCOLVAL - MIN(MAXCOLVAL,
                                        y*(MAXCOLVAL-k)/MAXCOLVAL+k);

                    PPM_ASSIGN(cmap->color[i], red, green, blue);
                }
            }
            chunk_end(ifp, iffid, chunksize);
        }
    }
}



static void
read_clut(FILE *        const ifp,
          IFF_ID        const iffid,
          unsigned long const chunksize,
          ColorMap *    const cmap) {

    if (chunksize != CLUTSize) {
        pm_message("invalid size for %s chunk - skipping it", 
                   ID2string(iffid));
        skip_chunk(ifp, iffid, chunksize);
    } else {
        long type;
        unsigned char * lut;
        unsigned long remainingChunksize;
        unsigned int i;

        type = get_big_long(ifp, iffid, &remainingChunksize);
        get_big_long(ifp, iffid, &remainingChunksize); /* skip reserved fld */

        MALLOCARRAY_NOFAIL(lut, 256);
        for( i = 0; i < 256; ++i )
            lut[i] = get_byte(ifp, iffid, &remainingChunksize);

        switch( type ) {
        case CLUT_MONO:
            cmap->monolut  = lut;
            break;
        case CLUT_RED:
            cmap->redlut   = lut;
            break;
        case CLUT_GREEN:
            cmap->greenlut = lut;
            break;
        case CLUT_BLUE:
            cmap->bluelut  = lut;
            break;
        default:
            pm_message("warning - %s type %ld not recognized",
                       ID2string(iffid), type);
            free(lut);
        }
    }
}



static BitMapHeader *
read_bmhd(FILE *        const ifP,
          IFF_ID        const iffid,
          unsigned long const chunksize) {

    BitMapHeader * bmhdP;

    if( chunksize != BitMapHeaderSize ) {
        pm_message("invalid size for %s chunk - skipping it", 
                   ID2string(iffid));
        skip_chunk(ifP, iffid, chunksize);
        bmhdP = NULL;
    } else {
        unsigned long remainingChunksize;

        MALLOCVAR_NOFAIL(bmhdP);

        remainingChunksize = chunksize;  /* initial value */
        
        bmhdP->w = get_big_short(ifP, iffid, &remainingChunksize);
        bmhdP->h = get_big_short(ifP, iffid, &remainingChunksize);
        bmhdP->x = get_big_short(ifP, iffid, &remainingChunksize);
        bmhdP->y = get_big_short(ifP, iffid, &remainingChunksize);
        bmhdP->nPlanes = get_byte(ifP, iffid, &remainingChunksize);
        bmhdP->masking = get_byte(ifP, iffid, &remainingChunksize);
        bmhdP->compression = get_byte(ifP, iffid, &remainingChunksize);
        bmhdP->flags = get_byte(ifP, iffid, &remainingChunksize);
        bmhdP->transparentColor =
            get_big_short(ifP, iffid, &remainingChunksize);
        bmhdP->xAspect = get_byte(ifP, iffid, &remainingChunksize);
        bmhdP->yAspect = get_byte(ifP, iffid, &remainingChunksize);
        bmhdP->pageWidth  = get_big_short(ifP, iffid, &remainingChunksize);
        bmhdP->pageHeight = get_big_short(ifP, iffid, &remainingChunksize);

        if( verbose ) {
            if( typeid == ID_ILBM )
                pm_message("dimensions: %dx%d, %d planes", 
                           bmhdP->w, bmhdP->h, bmhdP->nPlanes);
            else
                pm_message("dimensions: %dx%d", bmhdP->w, bmhdP->h);

            if( typeid == ID_ILBM || typeid == ID_PBM ) {
                pm_message("compression: %s",
                           bmhdP->compression <= cmpMAXKNOWN ?
                           cmpNAME[bmhdP->compression] : "unknown");

                switch( bmhdP->masking ) {
                case mskNone:
                    break;
                case mskHasMask:
                case mskHasTransparentColor:
                    if( !maskfile )
                        pm_message("use '-maskfile <filename>' "
                                   "to generate a PBM mask file from %s", 
                                   mskNAME[bmhdP->masking]);
                    break;
                case mskLasso:
                    pm_message("warning - masking type '%s' not recognized", 
                               mskNAME[bmhdP->masking]);
                    break;
                default:
                    pm_error("unknown masking type %d", bmhdP->masking);
                }
            }
            else    /* RGBN/RGB8 */
                if( !maskfile )
                    pm_message("use '-maskfile <filename>' "
                               "to generate a PBM mask file "
                               "from genlock bits");
        }

        /* fix aspect ratio */
        if( bmhdP->xAspect == 0 || bmhdP->yAspect == 0 ) {
            pm_message("warning - illegal aspect ratio %d:%d, using 1:1", 
                       bmhdP->xAspect, bmhdP->yAspect);
            bmhdP->xAspect = bmhdP->yAspect = 1;
        }

        if( bmhdP->xAspect != bmhdP->yAspect ) {
            pm_message("warning - non-square pixels; "
                       "to fix do a 'pnmscale -%cscale %g'",
                       bmhdP->xAspect > bmhdP->yAspect ? 'x' : 'y',
                       bmhdP->xAspect > bmhdP->yAspect ? 
                       (float)(bmhdP->xAspect)/bmhdP->yAspect : 
                       (float)(bmhdP->yAspect)/bmhdP->xAspect);
        }
    }
    return bmhdP;
}


/****************************************************************************
 ILBM functions
 ****************************************************************************/


static void
read_ilbm_plane(FILE *          const ifP,
                unsigned long * const remainingChunksizeP,
                int             const bytes,
                int             const compression) {

    unsigned char *ubp;
    int j, byte;
    int bytesRemaining;

    bytesRemaining = bytes;  /* initial value */

    switch(compression) {
        case cmpNone:
            read_bytes(ifP, bytesRemaining, ilbmrow,
                       ID_BODY, remainingChunksizeP);
            break;
        case cmpByteRun1:
            ubp = ilbmrow;
            do {
                byte = (int)get_byte(ifP, ID_BODY, remainingChunksizeP);
                if( byte <= 127 ) {
                    j = byte;
                    bytesRemaining -= (j+1);
                    if( bytesRemaining < 0 )
                        pm_error("error doing ByteRun1 decompression");
                    for( ; j >= 0; j-- )
                        *ubp++ = get_byte(ifP, ID_BODY, remainingChunksizeP);
                }
                else
                if ( byte != 128 ) {
                    j = 256 - byte;
                    bytesRemaining -= (j+1);
                    if( bytesRemaining < 0 )
                        pm_error("error doing ByteRun1 decompression");
                    byte = (int)get_byte(ifP, ID_BODY, remainingChunksizeP);
                    for( ; j >= 0; j-- )
                        *ubp++ = (unsigned char)byte;
                }
                /* 128 is a NOP */
            }
            while( bytesRemaining > 0 );
            break;
        default:
            pm_error("unknown compression type %d", compression);
    }
}


static const unsigned char bit_mask[] = {1, 2, 4, 8, 16, 32, 64, 128};

static void
decode_row(FILE *          const ifP,
           unsigned long * const remainingChunksizeP,
           rawtype *       const chunkyrow,
           int             const nPlanes,
           BitMapHeader *  const bmhdP) {

    int plane, col, cols, cbit, bytes;
    unsigned char *ilp;
    rawtype *chp;

    cols = bmhdP->w;
    bytes = RowBytes(cols);
    for( plane = 0; plane < nPlanes; plane++ ) {
        int mask;

        mask = 1 << plane;
        read_ilbm_plane(ifP, remainingChunksizeP, bytes, bmhdP->compression);

        ilp = ilbmrow;
        chp = chunkyrow;

        cbit = 7;
        for( col = 0; col < cols; col++, cbit--, chp++ ) {
            if( cbit < 0 ) {
                cbit = 7;
                ilp++;
            }
            if( *ilp & bit_mask[cbit] )
                *chp |= mask;
            else
                *chp &= ~mask;
        }
    }
}


static void
decode_mask(FILE *          const ifP,
            unsigned long * const remainingChunksizeP,
            rawtype *       const chunkyrow,
            BitMapHeader *  const bmhdP) {

    int col, cols, cbit;
    unsigned char *ilp;

    cols = bmhdP->w;
    switch( bmhdP->masking ) {
    case mskNone:
        break;
    case mskHasMask:        /* mask plane */
        read_ilbm_plane(ifP, remainingChunksizeP, RowBytes(cols), 
                        bmhdP->compression);
        if( maskfile ) {
            ilp = ilbmrow;
            cbit = 7;
            for( col = 0; col < cols; col++, cbit-- ) {
                if( cbit < 0 ) {
                    cbit = 7;
                    ilp++;
                }
                if( *ilp & bit_mask[cbit] )
                    maskrow[col] = PBM_BLACK;
                else
                    maskrow[col] = PBM_WHITE;
            }
            pbm_writepbmrow(maskfile, maskrow, cols, 0);
            wrotemask = 1;
        }
        break;
    case mskHasTransparentColor:
        if( !chunkyrow )
            pm_error("decode_mask(): chunkyrow == NULL - can't happen");
        
        if( maskfile ) {
            for( col = 0; col < cols; col++ ) {
                if( chunkyrow[col] == bmhdP->transparentColor )
                    maskrow[col] = PBM_WHITE;
                else
                    maskrow[col] = PBM_BLACK;
            }
            pbm_writepbmrow(maskfile, maskrow, cols, 0);
                wrotemask = 1;
        }
        break;
    case mskLasso:
        pm_error("This program does not know how to process Lasso masking");
        break;
    default:
        pm_error("decode_mask(): unknown masking type %d - can't happen", 
                 bmhdP->masking);
    }
}


/****************************************************************************
 Multipalette handling
 ****************************************************************************/


static void
multi_adjust(cmap, row, palchange)
    ColorMap *cmap;
    int row;
    PaletteChange *palchange;
{
    int i, reg;

    for( i = 0; palchange[i].reg != MP_REG_END; i++ ) {
        reg = palchange[i].reg;
        if( reg >= cmap->ncolors ) {
            pm_message("warning - palette change register out of range");
            pm_message("    row %d  change structure %d  reg=%d (max %d)", 
                       row, i, reg, cmap->ncolors-1);
            pm_message("    ignoring it...  "
                       "colors might get messed up from here");
        }
        else
        if( reg != MP_REG_IGNORE ) {
            PPM_ASSIGN(cmap->color[reg], 
                       palchange[i].r, palchange[i].g, palchange[i].b);
        }
    }
}

static void
multi_init(cmap, viewportmodes)
    ColorMap *cmap;
    long viewportmodes;
{
    if( cmap->mp_init )
        multi_adjust(cmap, -1, cmap->mp_init);
    if( !(viewportmodes & vmLACE) )
        cmap->mp_flags &= ~(MP_FLAGS_SKIPLACED);
}

static void
multi_update(cmap, row)
    ColorMap *cmap;
    int row;
{
    if( cmap->mp_flags & MP_FLAGS_SKIPLACED ) {
        if( ODD(row) )
            return;
        if( row/2 < cmap->mp_rows && cmap->mp_change[row/2] )
            multi_adjust(cmap, row, cmap->mp_change[row/2]);
    }
    else {
        if( row < cmap->mp_rows && cmap->mp_change[row] )
            multi_adjust(cmap, row, cmap->mp_change[row]);
    }
}

static void
multi_free(cmap)
    ColorMap *cmap;
{
    int i;

    if( cmap->mp_init ) {
        free(cmap->mp_init);
        cmap->mp_init = NULL;
    }
    if( cmap->mp_change ) {
        for( i = 0; i < cmap->mp_rows; i++ ) {
            if( cmap->mp_change[i] )
                free(cmap->mp_change[i]);
        }
        free(cmap->mp_change);
        cmap->mp_change = NULL;
    }
    cmap->mp_rows = 0;
    cmap->mp_type = 0;
    cmap->mp_flags = 0;
}



/****************************************************************************
 Colormap handling
 ****************************************************************************/



static void
analyzeCmapSamples(const ColorMap * const cmapP,
                   pixval *         const maxSampleP,
                   bool *           const shiftedP) {

    pixval       maxSample;
    bool         shifted;
    unsigned int i;
        
    for (i = 0, maxSample = 0, shifted = true; i < cmapP->ncolors; ++i) {
        pixval const r = PPM_GETR(cmapP->color[i]);
        pixval const g = PPM_GETG(cmapP->color[i]);
        pixval const b = PPM_GETB(cmapP->color[i]);

        maxSample = MAX(maxSample, MAX(r, MAX(g, b)));

        if (r & 0x0f || g & 0x0f || b & 0x0f)
            shifted = false;
    }
    *shiftedP   = shifted;
    *maxSampleP = maxSample;
}



static void
transformCmap(ColorMap * const cmapP) {

    pixval maxSample;
        /* The maximum sample value in *cmapP input */
    bool shifted;
        /* Samples in the *cmapP input appear to be 4 bit (maxval 15) original
           values shifted left 4 places to make 8 bit (maxval 255) samples.
        */

    analyzeCmapSamples(cmapP, &maxSample, &shifted);

    if (maxSample == 0)
        pm_message("warning - black colormap");
    else if (shifted || maxSample <= 15) {
        if (!adjustcolors) {
            pm_message("warning - probably %s4-bit colormap",
                       shifted ? "shifted " : "");
            pm_message("Use '-adjustcolors' to scale colormap to 8 bits");
        } else {
            unsigned int i;
            pm_message("scaling colormap to 8 bits");
            for (i = 0; i < cmapP->ncolors; ++i) {
                pixval r, g, b;
                r = PPM_GETR(cmapP->color[i]);
                g = PPM_GETG(cmapP->color[i]);
                b = PPM_GETB(cmapP->color[i]);
                if (shifted) {
                    r >>= 4;
                    g >>= 4;
                    b >>= 4;
                }
                r *= FACTOR_4BIT;
                g *= FACTOR_4BIT;
                b *= FACTOR_4BIT;
                PPM_ASSIGN(cmapP->color[i], r, g, b);
            }
        }
    }
}



static pixel *
transpColor(const BitMapHeader * const bmhdP,
            ColorMap *           const cmapP,
            const char *         const transpName,
            pixval               const maxval) {

    pixel * transpColorP;

    if (bmhdP) {
        if (bmhdP->masking == mskHasTransparentColor || 
            bmhdP->masking == mskLasso) {
            MALLOCVAR_NOFAIL(transpColorP);

            if (transpName)
                *transpColorP = ppm_parsecolor(transpName, maxval);
            else {
                unsigned short const transpIdx = bmhdP->transparentColor;
                if (HAS_COLORMAP(cmapP)) {
                    if (transpIdx >= cmapP->ncolors) {
                        pm_message("using default transparent color (black)");
                        PPM_ASSIGN(*transpColorP, 0, 0, 0);
                    } else
                        *transpColorP = cmapP->color[transpIdx];
                } else {
                    /* The color index is just a direct gray level */
                    PPM_ASSIGN(*transpColorP, transpIdx, transpIdx, transpIdx);
                }
            }
        } else
            transpColorP = NULL;
    } else
        transpColorP = NULL;

    return transpColorP;
}



static void
prepareCmap(const BitMapHeader * const bmhdP,
            ColorMap *           const cmapP) {
/*----------------------------------------------------------------------------
   This is a really ugly subroutine that 1) analyzes a colormap and its
   context (returning the analysis in global variables); and 2) modifies that
   color map, because it's really one type of data structure as input and
   another as output.
-----------------------------------------------------------------------------*/
    bool bmhdCmapOk;

    if (bmhdP)
        bmhdCmapOk = (bmhdP->flags & BMHD_FLAGS_CMAPOK);
    else
        bmhdCmapOk = false;

    if (HAS_COLORMAP(cmapP) && !bmhdCmapOk)
        transformCmap(cmapP);
}



static pixval
lookup_red(cmap, oldval)
    ColorMap *cmap;
    int oldval;
{
    if( cmap && cmap->redlut && oldval < 256 )
        return cmap->redlut[oldval];
    else
        return oldval;
}

static pixval
lookup_green(cmap, oldval)
    ColorMap *cmap;
    int oldval;
{
    if( cmap && cmap->greenlut && oldval < 256 )
        return cmap->greenlut[oldval];
    else
        return oldval;
}

static pixval
lookup_blue(cmap, oldval)
    ColorMap *cmap;
    int oldval;
{
    if( cmap && cmap->bluelut && oldval < 256 )
        return cmap->bluelut[oldval];
    else
        return oldval;
}

static pixval
lookup_mono(cmap, oldval)
    ColorMap *cmap;
    int oldval;
{
    if( cmap && cmap->monolut && oldval < 256 )
        return cmap->monolut[oldval];
    else
        return oldval;
}

static ColorMap *
ehbcmap(cmap)
    ColorMap *cmap;
{
    pixel *tempcolor = NULL;
    int i, col;

    col = cmap->ncolors;

    tempcolor = ppm_allocrow(col * 2);
    for( i = 0; i < col; i++ ) {
        tempcolor[i] = cmap->color[i];
        PPM_ASSIGN(tempcolor[col + i],  PPM_GETR(cmap->color[i]) / 2,
                                        PPM_GETG(cmap->color[i]) / 2,
                                        PPM_GETB(cmap->color[i]) / 2 );
    }
    ppm_freerow(cmap->color);
    cmap->color = tempcolor;
    cmap->ncolors *= 2;

    return cmap;
}



static pixval
lut_maxval(ColorMap * const cmap, 
           pixval     const maxval) {

    pixval retval;
    
    if (maxval >= 255)
        retval = maxval;
    else {
        if (!HAS_COLORLUT(cmap))
            retval = maxval;
        else {
            unsigned int i;
            unsigned char maxlut;
            maxlut = maxval;
            for( i = 0; i < maxval; i++ ) {
                if( cmap->redlut   && cmap->redlut[i]   > maxlut ) 
                    maxlut = cmap->redlut[i];
                if( cmap->greenlut && cmap->greenlut[i] > maxlut ) 
                    maxlut = cmap->greenlut[i];
                if( cmap->bluelut  && cmap->bluelut[i]  > maxlut ) 
                    maxlut = cmap->bluelut[i];
            }
            pm_message("warning - "
                       "%d-bit index into 8-bit color lookup table, "
                       "table maxval=%d", 
                       pm_maxvaltobits(maxval), maxlut);
            if( maxlut != maxval )
                retval = 255;
            else
                retval = maxval;
            pm_message("    assuming image maxval=%d", retval);
        }
    }
    return retval;
}



static void
get_color(cmap, idx, red, green, blue)
    ColorMap *cmap;
    int idx;
    pixval *red, *green, *blue;
{
    if( HAS_COLORMAP(cmap) ) {
        pixval r, g, b;

        if( idx >= cmap->ncolors )
            pm_error("color index out of range: %d (max %d)", 
                     idx, cmap->ncolors);
        r = PPM_GETR(cmap->color[idx]);
        g = PPM_GETG(cmap->color[idx]);
        b = PPM_GETB(cmap->color[idx]);

        *red    = lookup_red(cmap, r);
        *green  = lookup_green(cmap, g);
        *blue   = lookup_blue(cmap, b);
    }
    else {
        *red = *green = *blue = lookup_mono(cmap, idx);
    }
}


/****************************************************************************
 Conversion functions
 ****************************************************************************/

static void
std_to_ppm(FILE *         const ifp, 
           long           const chunksize, 
           BitMapHeader * const bmhdP, 
           ColorMap *     const cmap, 
           long           const viewportmodes);



static void
ham_to_ppm(FILE *         const ifp, 
           long           const chunksize, 
           BitMapHeader * const bmhdP, 
           ColorMap *     const cmap, 
           long           const viewportmodes) {

    int cols, rows, hambits, hammask, hamshift, hammask2, col, row;
    pixval maxval;
    rawtype *rawrow;
    unsigned char hamlut[256];

    cols = bmhdP->w;
    rows = bmhdP->h;
    hambits = bmhdP->nPlanes - 2;
    hammask = (1 << hambits) - 1;
    hamshift = 8 - hambits;
    hammask2 = (1 << hamshift) - 1;

    if( hambits > 8 || hambits < 1 ) {
        int const assumed_viewportmodes = viewportmodes & ~(vmHAM);

        pm_message("%d-plane HAM?? - interpreting image as a normal ILBM", 
                   bmhdP->nPlanes);
        std_to_ppm(ifp, chunksize, bmhdP, cmap, assumed_viewportmodes);
        return;
    } else {
        unsigned long remainingChunksize;
        pixel * transpColorP;

        pm_message("input is a %sHAM%d file", 
                   HAS_MULTIPALETTE(cmap) ? "multipalette " : "", 
                   bmhdP->nPlanes);

        if( HAS_COLORLUT(cmap) || HAS_MONOLUT(cmap) ) {
            pm_message("warning - color lookup tables ignored in HAM");
            if( cmap->redlut )      free(cmap->redlut);
            if( cmap->greenlut )    free(cmap->greenlut);
            if( cmap->bluelut )     free(cmap->bluelut);
            if( cmap->monolut )     free(cmap->monolut);
            cmap->redlut = cmap->greenlut = cmap->bluelut = 
                cmap->monolut = NULL;
        }
        if( !HAS_COLORMAP(cmap) ) {
            pm_message("no colormap - interpreting values as grayscale");
            maxval = pm_bitstomaxval(hambits);
            for( col = 0; col <= maxval; col++ )
                hamlut[col] = col * MAXCOLVAL / maxval;
            cmap->monolut = hamlut;
        }

        transpColorP = transpColor(bmhdP, cmap, transpName, MAXCOLVAL);

        if( HAS_MULTIPALETTE(cmap) )
            multi_init(cmap, viewportmodes);

        rawrow = alloc_rawrow(cols);

        ppm_writeppminit(stdout, cols, rows, MAXCOLVAL, 0);

        remainingChunksize = chunksize;  /* initial value */

        for (row = 0; row < rows; ++row) {
            pixval r, g, b;

            if( HAS_MULTIPALETTE(cmap) )
                multi_update(cmap, row);

            decode_row(ifp, &remainingChunksize, rawrow, bmhdP->nPlanes, bmhdP);
            decode_mask(ifp, &remainingChunksize, rawrow, bmhdP);

            r = g = b = 0;
            for( col = 0; col < cols; col++ ) {
                int idx = rawrow[col] & hammask;

                if( transpColorP && maskrow && maskrow[col] == PBM_WHITE )
                    pixelrow[col] = *transpColorP;
                else {
                    switch((rawrow[col] >> hambits) & 0x03) {
                    case HAMCODE_CMAP:
                        get_color(cmap, idx, &r, &g, &b);
                        break;
                    case HAMCODE_BLUE:
                        b = ((b & hammask2) | (idx << hamshift));
                        /*b = hamlut[idx];*/
                        break;
                    case HAMCODE_RED:
                        r = ((r & hammask2) | (idx << hamshift));
                        /*r = hamlut[idx];*/
                        break;
                    case HAMCODE_GREEN:
                        g = ((g & hammask2) | (idx << hamshift));
                        /*g = hamlut[idx];*/
                        break;
                    default:
                        pm_error("ham_to_ppm(): "
                                 "impossible HAM code - can't happen");
                    }
                    PPM_ASSIGN(pixelrow[col], r, g, b);
                }
            }
            ppm_writeppmrow(stdout, pixelrow, cols, MAXCOLVAL, 0);
        }
        chunk_end(ifp, ID_BODY, remainingChunksize);
    }
}



static void
std_to_ppm(FILE *         const ifP, 
           long           const chunksize, 
           BitMapHeader * const bmhdP, 
           ColorMap *     const cmap, 
           long           const viewportmodes) {

    if (viewportmodes & vmHAM) {
        ham_to_ppm(ifP, chunksize, bmhdP, cmap, viewportmodes);
    } else {
        unsigned int const cols = bmhdP->w;
        unsigned int const rows = bmhdP->h;

        rawtype *rawrow;
        unsigned int row, col;
        pixval maxval;
        unsigned long remainingChunksize;
        pixel * transpColorP;

        pm_message("input is a %d-plane %s%sILBM", bmhdP->nPlanes,
                   HAS_MULTIPALETTE(cmap) ? "multipalette " : "",
                   viewportmodes & vmEXTRA_HALFBRITE ? "EHB " : ""
            );

        if( bmhdP->nPlanes > MAXPLANES )
            pm_error("too many planes (max %d)", MAXPLANES);

        if( HAS_COLORMAP(cmap) ) {
            if( viewportmodes & vmEXTRA_HALFBRITE )
                ehbcmap(cmap);  /* Modifies *cmap */
            maxval = MAXCOLVAL;
        }
        else {
            pm_message("no colormap - interpreting values as grayscale");
            maxval = lut_maxval(cmap, pm_bitstomaxval(bmhdP->nPlanes));
            if( maxval > PPM_OVERALLMAXVAL )
                pm_error("nPlanes is too large");
        }

        transpColorP = transpColor(bmhdP, cmap, transpName, maxval);

        rawrow = alloc_rawrow(cols);

        if( HAS_MULTIPALETTE(cmap) )
            multi_init(cmap, viewportmodes);

        ppm_writeppminit( stdout, cols, rows, maxval, 0 );

        remainingChunksize = chunksize;  /* initial value */
    
        for (row = 0; row < rows; ++row) {

            if( HAS_MULTIPALETTE(cmap) )
                multi_update(cmap, row);

            decode_row(ifP, &remainingChunksize, rawrow, bmhdP->nPlanes, bmhdP);
            decode_mask(ifP, &remainingChunksize, rawrow, bmhdP);

            for( col = 0; col < cols; col++ ) {
                pixval r, g, b;
                if( transpColorP && maskrow && maskrow[col] == PBM_WHITE )
                    pixelrow[col] = *transpColorP;
                else {
                    get_color(cmap, rawrow[col], &r, &g, &b);
                    PPM_ASSIGN(pixelrow[col], r, g, b);
                }
            }
            ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
        }
        chunk_end(ifP, ID_BODY, remainingChunksize);
    }
}



static void
deep_to_ppm(FILE *         const ifP, 
            long           const chunksize, 
            BitMapHeader * const bmhdP, 
            ColorMap *     const cmap) {

    unsigned int const cols = bmhdP->w;
    unsigned int const rows = bmhdP->h;
    unsigned int const planespercolor = bmhdP->nPlanes / 3;

    unsigned int col, row;
    rawtype *Rrow, *Grow, *Brow;
    pixval maxval;
    unsigned long remainingChunksize;
    pixel * transpColorP;

    pm_message("input is a deep (%d-bit) ILBM", bmhdP->nPlanes);
    if( planespercolor > MAXPLANES )
        pm_error("too many planes (max %d)", MAXPLANES * 3);

    if( bmhdP->masking == mskHasTransparentColor || 
        bmhdP->masking == mskLasso ) {
        pm_message("masking type '%s' in a deep ILBM?? - ignoring it", 
                   mskNAME[bmhdP->masking]);
        bmhdP->masking = mskNone;
    }

    maxval = lut_maxval(cmap, pm_bitstomaxval(planespercolor));
    if( maxval > PPM_OVERALLMAXVAL )
        pm_error("nPlanes is too large");

    transpColorP = transpColor(bmhdP, cmap, transpName, maxval);
        
    Rrow = alloc_rawrow(cols);
    Grow = alloc_rawrow(cols);
    Brow = alloc_rawrow(cols);

    ppm_writeppminit(stdout, cols, rows, maxval, 0);

    remainingChunksize = chunksize;  /* initial value */

    for( row = 0; row < rows; row++ ) {
        decode_row(ifP, &remainingChunksize, Rrow, planespercolor, bmhdP);
        decode_row(ifP, &remainingChunksize, Grow, planespercolor, bmhdP);
        decode_row(ifP, &remainingChunksize, Brow, planespercolor, bmhdP);
        decode_mask(ifP, &remainingChunksize, NULL, bmhdP);

        for( col = 0; col < cols; col++ ) {
            if( transpColorP && maskrow && maskrow[col] == PBM_WHITE )
                pixelrow[col] = *transpColorP;
            else
                PPM_ASSIGN(pixelrow[col],   lookup_red(cmap, Rrow[col]),
                                            lookup_green(cmap, Grow[col]),
                                            lookup_blue(cmap, Brow[col]) );
        }
        ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
    }
    chunk_end(ifP, ID_BODY, remainingChunksize);
}



static void
dcol_to_ppm(FILE *         const ifP,
            long           const chunksize,
            BitMapHeader * const bmhdP,
            ColorMap *     const cmap,
            DirectColor *  const dcol) {

    unsigned int const cols = bmhdP->w;
    unsigned int const rows = bmhdP->h;
    unsigned int const redplanes   = dcol->r;
    unsigned int const greenplanes = dcol->g;
    unsigned int const blueplanes  = dcol->b;
    
    int col, row;
    rawtype *Rrow, *Grow, *Brow;
    pixval maxval, redmaxval, greenmaxval, bluemaxval;
    pixval *redtable, *greentable, *bluetable;
    unsigned long remainingChunksize;
    pixel * transpColorP;

    pm_message("input is a %d:%d:%d direct color ILBM",
                redplanes, greenplanes, blueplanes);

    if( redplanes > MAXPLANES || 
        blueplanes > MAXPLANES || 
        greenplanes > MAXPLANES )
        pm_error("too many planes (max %d per color component)", MAXPLANES);

    if( bmhdP->nPlanes != (redplanes + greenplanes + blueplanes) )
        pm_error("%s/%s plane number mismatch", 
                 ID2string(ID_BMHD), ID2string(ID_DCOL));

    if( bmhdP->masking == mskHasTransparentColor || 
        bmhdP->masking == mskLasso ) {
        pm_message("masking type '%s' in a direct color ILBM?? - ignoring it",
                   mskNAME[bmhdP->masking]);
        bmhdP->masking = mskNone;
    }

    if( HAS_COLORLUT(cmap) ) {
        pm_error("This program does not know how to process a %s chunk "
                 "in direct color", ID2string(ID_CLUT));
        cmap->redlut = cmap->greenlut = cmap->bluelut = NULL;
    }

    redmaxval   = pm_bitstomaxval(redplanes);
    greenmaxval = pm_bitstomaxval(greenplanes);
    bluemaxval  = pm_bitstomaxval(blueplanes);
    maxval = MAX(redmaxval, MAX(greenmaxval, bluemaxval));

    if( maxval > PPM_OVERALLMAXVAL )
        pm_error("too many planes");

    if( redmaxval != maxval || greenmaxval != maxval || bluemaxval != maxval )
        pm_message("scaling colors to %d bits", pm_maxvaltobits(maxval));
    
    MALLOCARRAY_NOFAIL(redtable,   redmaxval   +1);
    MALLOCARRAY_NOFAIL(greentable, greenmaxval +1);
    MALLOCARRAY_NOFAIL(bluetable,  bluemaxval  +1);

    {
        unsigned int i;
        for (i = 0; i <= redmaxval; ++i)
            redtable[i] = ROUNDDIV(i * maxval, redmaxval);
        for (i = 0; i <= greenmaxval; ++i)
            greentable[i] = ROUNDDIV(i * maxval, greenmaxval);
        for (i = 0; i <= bluemaxval; ++i)
            bluetable[i] = ROUNDDIV(i * maxval, bluemaxval);
    }
    transpColorP = transpColor(bmhdP, cmap, transpName, maxval);

    Rrow = alloc_rawrow(cols);
    Grow = alloc_rawrow(cols);
    Brow = alloc_rawrow(cols);

    ppm_writeppminit(stdout, cols, rows, maxval, 0);

    remainingChunksize = chunksize;  /* initial value */

    for( row = 0; row < rows; row++ ) {
        decode_row(ifP, &remainingChunksize, Rrow, redplanes, bmhdP);
        decode_row(ifP, &remainingChunksize, Grow, greenplanes, bmhdP);
        decode_row(ifP, &remainingChunksize, Brow, blueplanes, bmhdP);
        decode_mask(ifP, &remainingChunksize, NULL, bmhdP);

        for( col = 0; col < cols; col++ ) {
            if( transpColorP && maskrow && maskrow[col] == PBM_WHITE )
                pixelrow[col] = *transpColorP;
            else
                PPM_ASSIGN( pixelrow[col],  redtable[Rrow[col]],
                                            greentable[Grow[col]],
                                            bluetable[Brow[col]]   );
        }
        ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
    }
    chunk_end(ifP, ID_BODY, remainingChunksize);
}



static void
cmapToPpm(FILE *     const ofP,
            ColorMap * const cmapP) {

    ppm_colorrowtomapfile(ofP, cmapP->color, cmapP->ncolors, MAXCOLVAL);
}



static void
ipbm_to_ppm(FILE *         const ifP,
            long           const chunksize,
            BitMapHeader * const bmhdP,
            ColorMap *     const cmap,
            long           const viewportmodes) {

    unsigned int const cols = bmhdP->w;
    unsigned int const rows = bmhdP->h;

    int col, row;
    pixval maxval;
    unsigned long remainingChunksize;
    pixel * transpColorP;

    pm_message("input is a %sPBM ", 
               HAS_MULTIPALETTE(cmap) ? "multipalette " : "");

    if( bmhdP->nPlanes != 8 )
        pm_error("invalid number of planes for IFF-PBM: %d (must be 8)", 
                 bmhdP->nPlanes);

    if( bmhdP->masking == mskHasMask )
        pm_error("Image has a maskplane, which is invalid in IFF-PBM");

    if( HAS_COLORMAP(cmap) )
        maxval = MAXCOLVAL;
    else {
        pm_message("no colormap - interpreting values as grayscale");
        maxval = lut_maxval(cmap, pm_bitstomaxval(bmhdP->nPlanes));
    }

    transpColorP = transpColor(bmhdP, cmap, transpName, maxval);

    if( HAS_MULTIPALETTE(cmap) )
        multi_init(cmap, viewportmodes);

    MALLOCARRAY_NOFAIL(ilbmrow, cols);

    ppm_writeppminit(stdout, cols, rows, maxval, 0);

    remainingChunksize = chunksize;  /* initial value */

    for( row = 0; row < rows; row++ ) {
        if( HAS_MULTIPALETTE(cmap) )
            multi_update(cmap, row);
        
        read_ilbm_plane(ifP, &remainingChunksize, cols, bmhdP->compression);

        for( col = 0; col < cols; col++ ) {
            pixval r, g, b;
            if( transpColorP && maskrow && maskrow[col] == PBM_WHITE )
                pixelrow[col] = *transpColorP;
            else {
                get_color(cmap, ilbmrow[col], &r, &g, &b);
                PPM_ASSIGN(pixelrow[col], r, g, b);
            }
        }
        ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
    }
    chunk_end(ifP, ID_BODY, remainingChunksize);
}



static void
rgbn_to_ppm(FILE *         const ifP,
            long           const chunksize,
            BitMapHeader * const bmhdP,
            ColorMap *     const cmap  /* for CLUTs */
    ) {

    unsigned int const rows = bmhdP->h;
    unsigned int const cols = bmhdP->w;

    int row, col, count, genlock, tries;
    pixval r, g, b, maxval;
    unsigned long remainingChunksize;
    pixel * transpColorP;

    pm_message("input is a %d-bit RGB image", (typeid == ID_RGB8 ? 8 : 4));

    if( bmhdP->compression != 4 )
        pm_error("invalid compression mode for %s: %d (must be 4)", 
                 ID2string(typeid), bmhdP->compression);

    switch( typeid ) {
        case ID_RGBN:
            if( bmhdP->nPlanes != 13 )
                pm_error("invalid number of planes for %s: %d (must be 13)", 
                         ID2string(typeid), bmhdP->nPlanes);
            maxval = lut_maxval(cmap, 15);
            break;
        case ID_RGB8:
            if( bmhdP->nPlanes != 25 )
                pm_error("invalid number of planes for %s: %d (must be 25)", 
                         ID2string(typeid), bmhdP->nPlanes);
            maxval = 255;
            break;
        default:
            pm_error("rgbn_to_ppm(): invalid IFF ID %s - can't happen", 
                     ID2string(typeid));
    }

    transpColorP = transpColor(bmhdP, cmap, transpName, maxval);

    ppm_writeppminit(stdout, cols, rows, maxval, 0);

    remainingChunksize = chunksize;  /* initial value */
    count = 0;
    for( row = 0; row < rows; row++ ) {
        for( col = 0; col < cols; col++ ) {
            tries = 0;
            while( !count ) {
                if( typeid == ID_RGB8 ) {
                    r = lookup_red(cmap,   get_byte(ifP, ID_BODY, 
                                                    &remainingChunksize));
                    g = lookup_green(cmap, get_byte(ifP, ID_BODY,
                                                    &remainingChunksize));
                    b = lookup_blue(cmap,  get_byte(ifP, ID_BODY,
                                                    &remainingChunksize));
                    count = get_byte(ifP, ID_BODY, &remainingChunksize);
                    genlock = count & 0x80;
                    count &= 0x7f;
                }
                else {
                    int word;
                    word = get_big_short(ifP, ID_BODY, &remainingChunksize);
                    r = lookup_red(cmap, (word & 0xf000) >> 12);
                    g = lookup_green(cmap, (word & 0x0f00) >> 8);
                    b = lookup_blue(cmap, (word & 0x00f0) >> 4);
                    genlock = word & 0x0008;
                    count = word & 0x0007;
                }
                if( !count ) {
                    count = get_byte(ifP, ID_BODY, &remainingChunksize);
                    if( !count )
                        count =
                            get_big_short(ifP, ID_BODY, &remainingChunksize);
                        if( !count )
                            ++tries;
                }
            }
            if( tries ) {
                pm_message("warning - repeat count 0 at col %d row %d: "
                           "skipped %d RGB entr%s",
                            col, row, tries, (tries == 1 ? "y" : "ies"));
            }
            if( maskfile ) {
                /* genlock bit set -> transparent */
                if( genlock )
                    maskrow[col] = PBM_WHITE;
                else
                    maskrow[col] = PBM_BLACK;
            }
            if( transpColorP && maskrow && maskrow[col] == PBM_WHITE )
                pixelrow[col] = *transpColorP;
            else
                PPM_ASSIGN(pixelrow[col], r, g, b);
            --count;
        }
        ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
        if( maskfile ) {
            pbm_writepbmrow(maskfile, maskrow, cols, 0);
            wrotemask = 1;
        }
    }
    chunk_end(ifP, ID_BODY, remainingChunksize);
}

/****************************************************************************
 Multipalette chunk reader

    Currently there are three multipalette formats:
        SHAM - sliced HAM (obselete)
        CTBL - dynamic HAM/Hires (obselete)
        PCHG - palette change
    There is no official documentation available for SHAM and CTBL, so
   this is mostly guesswork from other sources and hexdumps of pictures...

    CTBL format (dynamic HAM/Hires):
        16 bigendian words per row (16 bit: 0000rrrrggggbbbb)
    This is simply an entire 4-bit colormap per row.
    I have no idea what the DYCP chunk is for.

    SHAM format (sliced HAM):
        1 word  - version info (?) - always 0
        16 bigendian words per row (16 bit: 0000rrrrggggbbbb)
    If the picture is laced, then there are only rows/2 changes, don't change
    palette on odd lines.

    PCHG format: A detailed description of this format is available
    from AmiNet as PCHGLib12.lha.

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

/* Turn big-endian 4-byte long and 2-byte short stored at x (unsigned char *)
 * into the native format of the CPU
 */
#define BIG_LONG(x) (   ((unsigned long)((x)[0]) << 24) + \
                        ((unsigned long)((x)[1]) << 16) + \
                        ((unsigned long)((x)[2]) <<  8) + \
                        ((unsigned long)((x)[3]) <<  0) )
#define BIG_WORD(x) (   ((unsigned short)((x)[0]) << 8) + \
                        ((unsigned short)((x)[1]) << 0) )



static void
read_4bit_mp(FILE *     const ifP,
             IFF_ID     const iffid,
             long       const chunksize,
             ColorMap * const cmap) {

    int row, rows, i, type;
    short data;
    unsigned long remainingChunksize;

    type = (iffid == ID_SHAM ? MP_TYPE_SHAM : MP_TYPE_CTBL);

    if( cmap->mp_type >= type ) {
        skip_chunk(ifP, iffid, chunksize);
    } else {
        if( cmap->mp_type )
            multi_free(cmap);
        cmap->mp_type = type;

        remainingChunksize = chunksize;  /* initial value */

        if( type == MP_TYPE_SHAM ) {
            cmap->mp_flags = MP_FLAGS_SKIPLACED;
            get_big_short(ifP, iffid, &remainingChunksize); /* skip first wd */
        }

        cmap->mp_rows = rows = remainingChunksize/32; /* sizeof(word) * 16 */
        MALLOCARRAY_NOFAIL(cmap->mp_change, rows);

        for( row = 0; row < rows; row++ ) {
            MALLOCARRAY_NOFAIL(cmap->mp_change[row], 17);   /* 16 + sentinel */
            for( i = 0; i < 16; i++ ) {
                data = get_big_short(ifP, iffid, &remainingChunksize);
                cmap->mp_change[row][i].reg = i;
                cmap->mp_change[row][i].r =
                    ((data & 0x0f00) >> 8) * FACTOR_4BIT;
                cmap->mp_change[row][i].g =
                    ((data & 0x00f0) >> 4) * FACTOR_4BIT;
                cmap->mp_change[row][i].b =
                    ((data & 0x000f) >> 0) * FACTOR_4BIT;
            }
            cmap->mp_change[row][16].reg = MP_REG_END;   /* sentinel */
        }
        chunk_end(ifP, iffid, remainingChunksize);
    }
}



static void
PCHG_DecompHuff(src, dest, tree, origsize)
    unsigned char *src, *dest;
    short *tree;
    unsigned long origsize;
{
    unsigned long i = 0, bits = 0;
    unsigned char thisbyte;
    short *p;

    p = tree;
    while( i < origsize ) {
        if( bits == 0 ) {
            thisbyte = *src++;
            bits = 8;
        }
        if( thisbyte & (1 << 7) ) {
            if( *p >= 0 ) {
                *dest++ = (unsigned char)*p;
                i++;
                p = tree;
            }
            else
                p += (*p / 2);
        }
        else {
            p--;
            if( *p > 0 && (*p & 0x100) ) {
                *dest++ = (unsigned char )*p;
                i++;
                p = tree;
            }
        }
        thisbyte <<= 1;
        bits--;
    }
}



static void
PCHG_Decompress(PCHGHeader *     const PCHG,
                PCHGCompHeader * const CompHdr,
                unsigned char *  const compdata,
                unsigned long    const compsize,
                unsigned char *  const comptree,
                unsigned char *  const data) {

    switch(PCHG->Compression) {
    case PCHG_COMP_HUFFMAN: {
        unsigned long const treesize = CompHdr->CompInfoSize;
        unsigned long const huffsize = treesize / 2;
        const bigend16 * const bigendComptree = (const void *)comptree;

        short * hufftree;
        unsigned long i;

        /* Convert big-endian 2-byte shorts to C shorts */

        MALLOCARRAY(hufftree, huffsize);

        if (!hufftree)
            pm_error("Couldn't get memory for %lu-byte Huffman tree",
                     huffsize);

        for (i = 0; i < huffsize; ++i)
            hufftree[i] = pm_uintFromBigend16(bigendComptree[i]);

        /* decompress the change structure data */
        PCHG_DecompHuff(compdata, data, &hufftree[huffsize-1], 
                        CompHdr->OriginalDataSize);
        
        free(hufftree);
    } break;
        default:
            pm_error("unknown PCHG compression type %d", PCHG->Compression);
    }
}


static void
PCHG_ConvertSmall(PCHG, cmap, mask, datasize)
    PCHGHeader *PCHG;
    ColorMap *cmap;
    unsigned char *mask;
    unsigned long datasize;
{
    unsigned char *data;
    unsigned char thismask;
    int bits, row, i, changes, masklen, reg;
    unsigned char ChangeCount16, ChangeCount32;
    unsigned short SmallChange;
    unsigned long totalchanges = 0;
    int changedlines = PCHG->ChangedLines;

    masklen = 4 * MaskLongWords(PCHG->LineCount);
    data = mask + masklen; datasize -= masklen;

    bits = 0;
    for( row = PCHG->StartLine; changedlines && row < 0; row++ ) {
        if( bits == 0 ) {
            if( masklen == 0 ) goto fail2;
            thismask = *mask++;
            --masklen;
            bits = 8;
        }
        if( thismask & (1<<7) ) {
            if( datasize < 2 ) goto fail;
            ChangeCount16 = *data++;
            ChangeCount32 = *data++;
            datasize -= 2;

            changes = ChangeCount16 + ChangeCount32;
            for( i = 0; i < changes; i++ ) {
                if( totalchanges >= PCHG->TotalChanges ) goto fail;
                if( datasize < 2 ) goto fail;
                SmallChange = BIG_WORD(data); data += 2; datasize -= 2;
                reg = ((SmallChange & 0xf000) >> 12) + 
                    (i >= ChangeCount16 ? 16 : 0);
                cmap->mp_init[reg - PCHG->MinReg].reg = reg;
                cmap->mp_init[reg - PCHG->MinReg].r = 
                    ((SmallChange & 0x0f00) >> 8) * FACTOR_4BIT;
                cmap->mp_init[reg - PCHG->MinReg].g = 
                    ((SmallChange & 0x00f0) >> 4) * FACTOR_4BIT;
                cmap->mp_init[reg - PCHG->MinReg].b = 
                    ((SmallChange & 0x000f) >> 0) * FACTOR_4BIT;
                ++totalchanges;
            }
            --changedlines;
        }
        thismask <<= 1;
        bits--;
    }

    for( row = PCHG->StartLine; changedlines && row < cmap->mp_rows; row++ ) {
        if( bits == 0 ) {
            if( masklen == 0 ) goto fail2;
            thismask = *mask++;
            --masklen;
            bits = 8;
        }
        if( thismask & (1<<7) ) {
            if( datasize < 2 ) goto fail;
            ChangeCount16 = *data++;
            ChangeCount32 = *data++;
            datasize -= 2;

            changes = ChangeCount16 + ChangeCount32;
            MALLOCARRAY_NOFAIL(cmap->mp_change[row], changes + 1);
            for( i = 0; i < changes; i++ ) {
                if( totalchanges >= PCHG->TotalChanges ) goto fail;
                if( datasize < 2 ) goto fail;
                SmallChange = BIG_WORD(data); data += 2; datasize -= 2;
                reg = ((SmallChange & 0xf000) >> 12) + 
                    (i >= ChangeCount16 ? 16 : 0);
                cmap->mp_change[row][i].reg = reg;
                cmap->mp_change[row][i].r = 
                    ((SmallChange & 0x0f00) >> 8) * FACTOR_4BIT;
                cmap->mp_change[row][i].g = 
                    ((SmallChange & 0x00f0) >> 4) * FACTOR_4BIT;
                cmap->mp_change[row][i].b = 
                    ((SmallChange & 0x000f) >> 0) * FACTOR_4BIT;
                ++totalchanges;
            }
            cmap->mp_change[row][changes].reg = MP_REG_END;
            --changedlines;
        }
        thismask <<= 1;
        bits--;
    }
    if( totalchanges != PCHG->TotalChanges )
        pm_message("warning - got %ld change structures, "
                   "chunk header reports %ld", 
                   totalchanges, PCHG->TotalChanges);
    return;
fail:
    pm_error("insufficient data in SmallLineChanges structures");
fail2:
    pm_error("insufficient data in line mask");
}



static void
PCHG_ConvertBig(PCHGHeader *    const PCHG,
                ColorMap *      const cmap,
                unsigned char * const maskStart,
                unsigned long   const datasize) {

    unsigned char * data;
    unsigned char thismask;
    int bits;
    unsigned int row;
    int changes;
    int masklen;
    int reg;
    unsigned long totalchanges;
    int changedlines;
    unsigned long dataRemaining;
    unsigned char * mask;

    mask = maskStart;  /* initial value */
    dataRemaining = datasize;  /* initial value */
    changedlines = PCHG->ChangedLines;  /* initial value */
    totalchanges = 0;  /* initial value */

    masklen = 4 * MaskLongWords(PCHG->LineCount);
    data = mask + masklen; dataRemaining -= masklen;

    for (row = PCHG->StartLine, bits = 0; changedlines && row < 0; ++row) {
        if (bits == 0) {
            if (masklen == 0)
                pm_error("insufficient data in line mask");
            thismask = *mask++;
            --masklen;
            bits = 8;
        }
        if (thismask & (1<<7)) {
            unsigned int i;

            if (dataRemaining < 2)
                pm_error("insufficient data in BigLineChanges structures");

            changes = BIG_WORD(data); data += 2; dataRemaining -= 2;

            for (i = 0; i < changes; ++i) {
                if (totalchanges >= PCHG->TotalChanges)
                    pm_error("insufficient data in BigLineChanges structures");

                if (dataRemaining < 6)
                    pm_error("insufficient data in BigLineChanges structures");

                reg = BIG_WORD(data); data += 2;
                cmap->mp_init[reg - PCHG->MinReg].reg = reg;
                ++data; /* skip alpha */
                cmap->mp_init[reg - PCHG->MinReg].r = *data++;
                cmap->mp_init[reg - PCHG->MinReg].b = *data++;  /* yes, RBG */
                cmap->mp_init[reg - PCHG->MinReg].g = *data++;
                dataRemaining -= 6;
                ++totalchanges;
            }
            --changedlines;
        }
        thismask <<= 1;
        --bits;
    }

    for (row = PCHG->StartLine; changedlines && row < cmap->mp_rows; ++row) {
        if (bits == 0) {
            if (masklen == 0)
                pm_error("insufficient data in line mask");

            thismask = *mask++;
            --masklen;
            bits = 8;
        }
        if (thismask & (1<<7)) {
            unsigned int i;

            if (dataRemaining < 2)
                pm_error("insufficient data in BigLineChanges structures");

            changes = BIG_WORD(data); data += 2; dataRemaining -= 2;

            MALLOCARRAY_NOFAIL(cmap->mp_change[row], changes + 1);
            for (i = 0; i < changes; ++i) {
                if (totalchanges >= PCHG->TotalChanges)
                    pm_error("insufficient data in BigLineChanges structures");

                if (dataRemaining < 6)
                    pm_error("insufficient data in BigLineChanges structures");

                reg = BIG_WORD(data); data += 2;
                cmap->mp_change[row][i].reg = reg;
                ++data; /* skip alpha */
                cmap->mp_change[row][i].r = *data++;
                cmap->mp_change[row][i].b = *data++;    /* yes, RBG */
                cmap->mp_change[row][i].g = *data++;
                dataRemaining -= 6;
                ++totalchanges;
            }
            cmap->mp_change[row][changes].reg = MP_REG_END;
            --changedlines;
        }
        thismask <<= 1;
        --bits;
    }
    if (totalchanges != PCHG->TotalChanges)
        pm_message("warning - got %ld change structures, "
                   "chunk header reports %ld", 
                   totalchanges, PCHG->TotalChanges);
}



static void
read_pchg(FILE *     const ifp,
          IFF_ID     const iffid,
          long       const chunksize,
          ColorMap * const cmap) {

    if( cmap->mp_type >= MP_TYPE_PCHG ) {
        skip_chunk(ifp, iffid, chunksize);
    } else {
        PCHGHeader      PCHG;
        unsigned char   *data;
        unsigned long   datasize;
        unsigned long   remainingChunksize;
        int i;

        if( cmap->mp_type )
            multi_free(cmap);
        cmap->mp_type = MP_TYPE_PCHG;

        remainingChunksize = chunksize;  /* initial value */

        PCHG.Compression = get_big_short(ifp, iffid, &remainingChunksize);
        PCHG.Flags       = get_big_short(ifp, iffid, &remainingChunksize);
        PCHG.StartLine   = get_big_short(ifp, iffid, &remainingChunksize);
        PCHG.LineCount   = get_big_short(ifp, iffid, &remainingChunksize);
        PCHG.ChangedLines= get_big_short(ifp, iffid, &remainingChunksize);
        PCHG.MinReg      = get_big_short(ifp, iffid, &remainingChunksize);
        PCHG.MaxReg      = get_big_short(ifp, iffid, &remainingChunksize);
        PCHG.MaxChanges  = get_big_short(ifp, iffid, &remainingChunksize);
        PCHG.TotalChanges= get_big_long(ifp, iffid, &remainingChunksize);

#ifdef DEBUG
        pm_message("PCHG StartLine   : %d", PCHG.StartLine);
        pm_message("PCHG LineCount   : %d", PCHG.LineCount);
        pm_message("PCHG ChangedLines: %d", PCHG.ChangedLines);
        pm_message("PCHG TotalChanges: %d", PCHG.TotalChanges);
#endif

        if( PCHG.Compression != PCHG_COMP_NONE ) {
            PCHGCompHeader  CompHdr;
            unsigned char *compdata, *comptree;
            long treesize, compsize;

            CompHdr.CompInfoSize     =
                get_big_long(ifp, iffid, &remainingChunksize);
            CompHdr.OriginalDataSize =
                get_big_long(ifp, iffid, &remainingChunksize);

            treesize = CompHdr.CompInfoSize;
            MALLOCARRAY_NOFAIL(comptree, treesize);
            read_bytes(ifp, treesize, comptree, iffid, &remainingChunksize);

            compsize = remainingChunksize;
            MALLOCARRAY_NOFAIL(compdata, compsize);
            read_bytes(ifp, compsize, compdata, iffid, &remainingChunksize);

            datasize = CompHdr.OriginalDataSize;
            MALLOCARRAY_NOFAIL(data, datasize);
            PCHG_Decompress(&PCHG, &CompHdr, compdata, 
                            compsize, comptree, data);

            free(comptree);
            free(compdata);
        } else {
#ifdef DEBUG
            pm_message("uncompressed PCHG");
#endif
            datasize = remainingChunksize;
            MALLOCARRAY_NOFAIL(data, datasize);
            read_bytes(ifp, datasize, data, iffid, &remainingChunksize);
        }

        if( PCHG.Flags & PCHGF_USE_ALPHA )
            pm_message("warning - ignoring PCHG alpha channel because "
                       "this program doesn't know what to do with it");

        cmap->mp_rows = PCHG.StartLine + PCHG.LineCount;
        MALLOCARRAY_NOFAIL(cmap->mp_change, cmap->mp_rows);
        for( i = 0; i < cmap->mp_rows; i++ )
            cmap->mp_change[i] = NULL;
        if( PCHG.StartLine < 0 ) {
            int nch;
            nch = PCHG.MaxReg - PCHG.MinReg +1;
            MALLOCARRAY_NOFAIL(cmap->mp_init, nch + 1);
            for( i = 0; i < nch; i++ )
                cmap->mp_init[i].reg = MP_REG_IGNORE;
            cmap->mp_init[nch].reg = MP_REG_END;
        }

        if( PCHG.Flags & PCHGF_12BIT ) {
#ifdef DEBUG
            pm_message("SmallLineChanges");
#endif
            PCHG_ConvertSmall(&PCHG, cmap, data, datasize);
        }
        else {
            if( PCHG.Flags & PCHGF_32BIT ) {
#ifdef DEBUG
                pm_message("BigLineChanges");
#endif
                PCHG_ConvertBig(&PCHG, cmap, data, datasize);
            }
            else
                pm_error("unknown palette changes structure "
                         "format in %s chunk", 
                         ID2string(iffid));
        }
        free(data);
        chunk_end(ifp, iffid, remainingChunksize);
    }
}



static bool
ignored_iffid(IFF_ID       const iffid,
              IFF_ID       const ignorelist[],
              unsigned int const ignorecount) {

    bool ignore;

    unsigned int i;
    ignore = FALSE;  /* initial assumption */
    for( i = 0; i < ignorecount && !ignore; i++ ) {
        if( iffid == ignorelist[i] )
            ignore = TRUE;
    }
    return ignore;
}



static void 
process_body( FILE *          const ifp,
              long            const chunksize,
              BitMapHeader *  const bmhdP,
              ColorMap *      const cmap,
              FILE *          const maskfile,
              int             const fakeviewport,
              int             const isdeepopt,
              DirectColor *   const dcol,
              int *           const viewportmodesP) {
    
    if( bmhdP == NULL )
        pm_error("%s chunk without %s chunk", 
                 ID2string(ID_BODY), ID2string(ID_BMHD));

    prepareCmap(bmhdP, cmap);

    pixelrow = ppm_allocrow(bmhdP->w);
    if( maskfile ) {
        maskrow = pbm_allocrow(bmhdP->w);
        pbm_writepbminit(maskfile, bmhdP->w, bmhdP->h, 0);
    }

    if( typeid == ID_ILBM ) {
        int isdeep;

        MALLOCARRAY_NOFAIL(ilbmrow, RowBytes(bmhdP->w));
        *viewportmodesP |= fakeviewport;      /* -isham/-isehb */

        if( isdeepopt > 0 && (bmhdP->nPlanes % 3 != 0) ) {
            pm_message("cannot interpret %d-plane image as 'deep' "
                       "(# of planes must be divisible by 3)", 
                       bmhdP->nPlanes);
            isdeep = 0;
        } else
            isdeep = isdeepopt;
        
        if( isdeep > 0 )
            deep_to_ppm(ifp, chunksize, bmhdP, cmap);
        else if( dcol )
            dcol_to_ppm(ifp, chunksize, bmhdP, cmap, dcol);
        else if( bmhdP->nPlanes > 8 ) {
            if( bmhdP->nPlanes <= 16 && HAS_COLORMAP(cmap) )
                std_to_ppm(ifp, chunksize, bmhdP, cmap, *viewportmodesP);
            else if( isdeep >= 0 && (bmhdP->nPlanes % 3 == 0) )
                deep_to_ppm(ifp, chunksize, bmhdP, cmap);
            else if( bmhdP->nPlanes <= 16 )   
                /* will be interpreted as grayscale */
                std_to_ppm(ifp, chunksize, bmhdP, cmap, *viewportmodesP);
            else
                pm_error("don't know how to interpret %d-plane image", 
                         bmhdP->nPlanes);
        } else
            std_to_ppm(ifp, chunksize, bmhdP, cmap, *viewportmodesP);
    } else if( typeid == ID_PBM )
        ipbm_to_ppm(ifp, chunksize, bmhdP, cmap, *viewportmodesP);
    else   /* RGBN or RGB8 */
        rgbn_to_ppm(ifp, chunksize, bmhdP, cmap);
}



static void 
processChunk(FILE *          const ifP,
             long            const formsize,
             IFF_ID          const ignorelist[],
             unsigned int    const ignorecount,
             int             const fakeviewport,
             int             const viewportmask,
             int             const isdeepopt,
             bool            const cmaponly,
             bool *          const bodyChunkProcessedP,
             bool *          const endchunkP,
             BitMapHeader ** const bmhdP,
             ColorMap *      const cmap,
             DirectColor **  const dcolP,
             int *           const viewportmodesP,
             long *          const bytesReadP
    ) {

    IFF_ID iffid;
    long chunksize;
    long bytesread;

    bytesread = 0;

    iffid = get_big_long(ifP, ID_FORM, NULL);
    chunksize = get_big_long(ifP, iffid, NULL);
    bytesread += 8;

    if (debug)
        pm_message("reading %s chunk: %ld bytes", ID2string(iffid), chunksize);

    if (ignored_iffid(iffid, ignorelist, ignorecount)) {
        pm_message("ignoring %s chunk", ID2string(iffid));
        skip_chunk(ifP, iffid, chunksize);
    } else if (iffid == ID_END) {
        /* END chunks are not officially valid in IFF, but
           suggested as a future expansion for stream-writing,
           see Amiga RKM Devices, 3rd Ed, page 376 
        */
        if (chunksize != 0 ) {
            pm_message("warning - non-0 %s chunk", ID2string(iffid));
            skip_chunk(ifP, iffid, chunksize);
        }
        if (formsize != 0xffffffff)
            pm_message("warning - %s chunk with FORM size 0x%08lx "
                       "(should be 0x%08x)",
                       ID2string(iffid), formsize, 0xffffffff);
        *endchunkP = 1;
    } else if (*bodyChunkProcessedP) {
        pm_message("%s chunk found after %s chunk - skipping", 
                   ID2string(iffid), ID2string(ID_BODY));
        skip_chunk(ifP, iffid, chunksize);
    } else
        switch (iffid) {
        case ID_BMHD:
            *bmhdP = read_bmhd(ifP, iffid, chunksize);
            break;
        case ID_CMAP:
            read_cmap(ifP, iffid, chunksize, cmap);
            break;
        case ID_CMYK:
            read_cmyk(ifP, iffid, chunksize, cmap);
            break;
        case ID_CLUT:
            read_clut(ifP, iffid, chunksize, cmap);
            break;
        case ID_CAMG:
            if (chunksize != CAMGChunkSize)
                pm_error("%s chunk size mismatch", ID2string(iffid));
            *viewportmodesP = get_big_long(ifP, ID_CAMG, NULL);
            *viewportmodesP &= viewportmask;      /* -isnotham/-isnotehb */
            break;
        case ID_PCHG:
            read_pchg(ifP, iffid, chunksize, cmap);
            break;
        case ID_CTBL:
        case ID_SHAM:
            read_4bit_mp(ifP, iffid, chunksize, cmap);
            break;
        case ID_DCOL:
            if (chunksize != DirectColorSize)
                pm_error("%s chunk size mismatch", ID2string(iffid));
            MALLOCVAR_NOFAIL(*dcolP);
            (*dcolP)->r = get_byte(ifP, iffid, NULL);
            (*dcolP)->g = get_byte(ifP, iffid, NULL);
            (*dcolP)->b = get_byte(ifP, iffid, NULL);
            get_byte(ifP, iffid, NULL);       /* skip pad byte */
            break;
        case ID_BODY: 
            if (cmaponly || (*bmhdP && (*bmhdP)->nPlanes == 0))
                skip_chunk(ifP, ID_BODY,  chunksize);
            else {
                process_body(ifP, chunksize, *bmhdP, cmap, 
                             maskfile, fakeviewport, isdeepopt, *dcolP,
                             viewportmodesP);

                *bodyChunkProcessedP = TRUE;
            } break;
        case ID_GRAB:   case ID_DEST:   case ID_SPRT:   case ID_CRNG:
        case ID_CCRT:   case ID_DYCP:   case ID_DPPV:   case ID_DRNG:
        case ID_EPSF:   case ID_JUNK:   case ID_CNAM:   case ID_PRVW:
        case ID_TINY:   case ID_DPPS:
            skip_chunk(ifP, iffid, chunksize);
            break;
        case ID_copy:   case ID_AUTH:   case ID_NAME:   case ID_ANNO:
        case ID_TEXT:   case ID_FVER:
            if (verbose)
                display_chunk(ifP, iffid, chunksize);
            else
                skip_chunk(ifP, iffid, chunksize);
            break;
        case ID_DPI: {
            int x, y;

            x = get_big_short(ifP, ID_DPI, NULL);
            y = get_big_short(ifP, ID_DPI, NULL);
            if (verbose)
                pm_message("%s chunk:  dpi_x = %d    dpi_y = %d", 
                           ID2string(ID_DPI), x, y);
        } break;
        default:
            pm_message("unknown chunk type %s - skipping", 
                       ID2string(iffid));
            skip_chunk(ifP, iffid, chunksize);
            break;
        }

    bytesread += chunksize;

    if (ODD(chunksize)) {
        get_byte(ifP, iffid, NULL);
        bytesread += 1;
    } 
    *bytesReadP = bytesread;
}



static void
maybeWriteColorMap(FILE *               const ofP,
                   const BitMapHeader * const bmhdP,
                   ColorMap *           const cmapP,
                   bool                 const bodyChunkProcessed,
                   bool                 const cmaponly) {
/*----------------------------------------------------------------------------
   Write to file *ofP the color map *cmapP as a PPM, if appropriate.

   The logic (not just here -- in the program as a whole) for deciding whether
   to write the image or the colormap is quite twisted.  If I thought anyone
   was actually using this program, I would take the time to straighten it
   out.

   What's really sick about this subroutine is that in choosing to write
   a color map, it has to know that Caller hasn't already written
   the image.  Huge modularity violation.
-----------------------------------------------------------------------------*/
    if (cmaponly) {
        if (HAS_COLORMAP(cmapP)) {
            prepareCmap(bmhdP, cmapP);
            cmapToPpm(ofP, cmapP);
        } else
            pm_error("You specified -cmaponly, but the ILBM "
                     "has no colormap");
    } else if (bmhdP && bmhdP->nPlanes == 0) {
        if (HAS_COLORMAP(cmapP)) {
            prepareCmap(bmhdP, cmapP);
            cmapToPpm(ofP, cmapP);
        } else
            pm_error("ILBM has neither a color map nor color planes");
    } else if (!bodyChunkProcessed) {
        if (HAS_COLORMAP(cmapP)) {
            pm_message("input is a colormap file");
            prepareCmap(bmhdP, cmapP);
            cmapToPpm(ofP, cmapP);
        } else
            pm_error("ILBM has neither %s or %s chunk", 
                     ID2string(ID_BODY), ID2string(ID_CMAP));
    }
}



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

    FILE * ifP;
    int argn;
    short cmaponly = 0, isdeepopt = 0;
    bool endchunk;
    bool bodyChunkProcessed;
    long formsize, bytesread;
    int viewportmodes = 0, fakeviewport = 0, viewportmask;
    IFF_ID firstIffid;
    BitMapHeader *bmhdP = NULL;
    ColorMap * cmap;
    DirectColor *dcol = NULL;
#define MAX_IGNORE  16
    IFF_ID ignorelist[MAX_IGNORE];
    int ignorecount = 0;
    char *maskname;
    const char * const usage =
        "[-verbose] [-ignore <chunkID> [-ignore <chunkID>] ...] "
        "[-isham|-isehb|-isdeep|-isnotham|-isnotehb|-isnotdeep] "
        "[-cmaponly] [-adjustcolors] "
        "[-transparent <color>] [-maskfile <filename>] [ilbmfile]";
    ppm_init(&argc, argv);

    viewportmask = 0xffffffff;

    argn = 1;
    while( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' ) {
        if( pm_keymatch(argv[argn], "-verbose", 2) )
            verbose = 1;
        else if( pm_keymatch(argv[argn], "-noverbose", 4) )
            verbose = 0;
        else if( pm_keymatch(argv[argn], "-isham", 4) )
            fakeviewport |= vmHAM;
        else if( pm_keymatch(argv[argn], "-isehb", 4) )
            fakeviewport |= vmEXTRA_HALFBRITE;
        else if( pm_keymatch(argv[argn], "-isdeep", 4) )
            isdeepopt = 1;
        else if( pm_keymatch(argv[argn], "-isnotham", 7) )
            viewportmask &= ~(vmHAM);
        else if( pm_keymatch(argv[argn], "-isnotehb", 7) )
            viewportmask &= ~(vmEXTRA_HALFBRITE);
        else if( pm_keymatch(argv[argn], "-isnotdeep", 7) )
            isdeepopt = -1;
        else if( pm_keymatch(argv[argn], "-cmaponly", 2) )
            cmaponly = 1;
        else if( pm_keymatch(argv[argn], "-adjustcolors", 2) )
            adjustcolors = 1;
        else if( pm_keymatch(argv[argn], "-noadjustcolors", 4) )
            adjustcolors = 0;
        else  if( pm_keymatch(argv[argn], "-transparent", 2) ) {
            if( ++argn >= argc )
                pm_usage(usage);
            transpName = argv[argn];
        } else if( pm_keymatch(argv[argn], "-maskfile", 2) ) {
            if( ++argn >= argc )
                pm_usage(usage);
            maskname = argv[argn];
            maskfile = pm_openw(maskname);
        } else if( pm_keymatch(argv[argn], "-ignore", 2) ) {
            if( ++argn >= argc )
                pm_usage(usage);
            if( strlen(argv[argn]) != 4 )
                pm_error("'-ignore' option needs a 4 byte chunk ID string "
                         "as argument");
            if( ignorecount >= MAX_IGNORE )
                pm_error("max %d chunk IDs to ignore", MAX_IGNORE);
            ignorelist[ignorecount++] = 
                MAKE_ID(argv[argn][0], argv[argn][1], argv[argn][2], 
                        argv[argn][3]);
        } else
            pm_usage(usage);
        ++argn;
    }    

    if( argn < argc ) {
        ifP = pm_openr( argv[argn] );
        argn++;
    } else
        ifP = stdin;

    if( argn != argc )
        pm_usage(usage);

    /* Read in the ILBM file. */

    firstIffid = get_big_long(ifP, ID_FORM, NULL);
    if (firstIffid != ID_FORM)
        pm_error("input is not a FORM type IFF file");
    formsize = get_big_long(ifP, ID_FORM, NULL);
    typeid = get_big_long(ifP, ID_FORM, NULL);
    if (typeid != ID_ILBM && typeid != ID_RGBN && typeid != ID_RGB8 && 
        typeid != ID_PBM)
        pm_error("input is not an ILBM, RGBN, RGB8 or PBM "
                 "type FORM IFF file");
    bytesread = 4;  /* FORM and formsize do not count */

    cmap = alloc_cmap();

    /* Main loop, parsing the IFF FORM. */
    bodyChunkProcessed = FALSE;
    endchunk = FALSE;
    while (!endchunk && formsize-bytesread >= 8) {
        long bytesReadForChunk;

        processChunk(ifP, formsize, ignorelist, ignorecount,
                     fakeviewport, viewportmask,
                     isdeepopt, cmaponly,
                     &bodyChunkProcessed,
                     &endchunk, &bmhdP, cmap, &dcol,
                     &viewportmodes, &bytesReadForChunk);

        bytesread += bytesReadForChunk;
    }

    if (maskfile) {
        pm_close(maskfile);
        if (!wrotemask)
            remove(maskname);
        pbm_freerow(maskrow);
    }

    maybeWriteColorMap(stdout, bmhdP, cmap, bodyChunkProcessed, cmaponly);

    {
        unsigned int skipped;
        
        for (skipped = 0; fgetc(ifP) != EOF; ++skipped)
            ++bytesread;

        if (skipped > 0)
            pm_message("skipped %u extraneous byte%s after last chunk",
                       skipped, (skipped == 1 ? "" : "s"));
    }
    pm_close(ifP);

    if (!endchunk && bytesread != formsize) {
        pm_message("warning - file length/FORM size field mismatch "
                   "(%ld != %ld+8)",
                   bytesread+8 /* FORM+size */, formsize);
    }

    return 0;
}