summaryrefslogtreecommitdiff
blob: c3028160effd612e5cd6276194ba80e2a09064fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
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
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
/*====================================================================*
 -  Copyright (C) 2001 Leptonica.  All rights reserved.
 -
 -  Redistribution and use in source and binary forms, with or without
 -  modification, are permitted provided that the following conditions
 -  are met:
 -  1. Redistributions of source code must retain the above copyright
 -     notice, this list of conditions and the following disclaimer.
 -  2. Redistributions in binary form must reproduce the above
 -     copyright notice, this list of conditions and the following
 -     disclaimer in the documentation and/or other materials
 -     provided with the distribution.
 -
 -  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 -  ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 -  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 -  A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL ANY
 -  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 -  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 -  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 -  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 -  OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 -  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 -  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *====================================================================*/

/*!
 * \file tiffio.c
 * <pre>
 *
 *     TIFFClientOpen() wrappers for FILE*:
 *      static tsize_t    lept_read_proc()
 *      static tsize_t    lept_write_proc()
 *      static toff_t     lept_seek_proc()
 *      static int        lept_close_proc()
 *      static toff_t     lept_size_proc()
 *
 *     Reading tiff:
 *             PIX       *pixReadTiff()             [ special top level ]
 *             PIX       *pixReadStreamTiff()
 *      static PIX       *pixReadFromTiffStream()
 *
 *     Writing tiff:
 *             l_int32    pixWriteTiff()            [ special top level ]
 *             l_int32    pixWriteTiffCustom()      [ special top level ]
 *             l_int32    pixWriteStreamTiff()
 *             l_int32    pixWriteStreamTiffWA()
 *      static l_int32    pixWriteToTiffStream()
 *      static l_int32    writeCustomTiffTags()
 *
 *     Reading and writing multipage tiff
 *             PIX       *pixReadFromMultipageTiff()
 *             PIXA      *pixaReadMultipageTiff()   [ special top level ]
 *             l_int32    pixaWriteMultipageTiff()  [ special top level ]
 *             l_int32    writeMultipageTiff()      [ special top level ]
 *             l_int32    writeMultipageTiffSA()
 *
 *     Information about tiff file
 *             l_int32    fprintTiffInfo()
 *             l_int32    tiffGetCount()
 *             l_int32    getTiffResolution()
 *      static l_int32    getTiffStreamResolution()
 *             l_int32    readHeaderTiff()
 *             l_int32    freadHeaderTiff()
 *             l_int32    readHeaderMemTiff()
 *      static l_int32    tiffReadHeaderTiff()
 *             l_int32    findTiffCompression()
 *      static l_int32    getTiffCompressedFormat()
 *
 *     Extraction of tiff g4 data:
 *             l_int32    extractG4DataFromFile()
 *
 *     Open tiff stream from file stream
 *      static TIFF      *fopenTiff()
 *
 *     Wrapper for TIFFOpen:
 *      static TIFF      *openTiff()
 *
 *     Memory I/O: reading memory --> pix and writing pix --> memory
 *             [10 static helper functions]
 *             PIX       *pixReadMemTiff();
 *             PIX       *pixReadMemFromMultipageTiff();
 *             PIXA      *pixaReadMemMultipageTiff()    [ special top level ]
 *             l_int32    pixaWriteMemMultipageTiff()   [ special top level ]
 *             l_int32    pixWriteMemTiff();
 *             l_int32    pixWriteMemTiffCustom();
 *
 *  Note 1: To include all necessary functions, use libtiff version 3.7.4
 *          (from 2005) or later.
 *  Note 2: What compression methods in tiff are supported?
 *          * We support most methods that are fully implemented in the
 *            tiff library, such as G3, G4, RLE and LZW.
 *          * The exception is the old-style jpeg tiff format (OJPEG), which
 *            is not supported.
 *          * We support only one format, ZIP, that uses an external library.
 *          * At present we do not support WEBP in tiff, which uses
 *            libwebp and was added in tifflib 4.1.0 in 2019.
 *  Note 3: On Windows with 2 bpp or 4 bpp images, the bytes in the
 *          tiff-compressed file depend on the pad bits, but not on the
 *          decoded raster image when read.  Because it is sometimes
 *          convenient to use a golden file with a byte-by-byte check
 *          to verify invariance, we set the pad bits to 0 before writing,
 *          in pixWriteToTiffStream().
 * </pre>
 */

#ifdef HAVE_CONFIG_H
#include <config_auto.h>
#endif  /* HAVE_CONFIG_H */

#include <string.h>
#include <math.h>   /* for isnan */
#include <sys/types.h>
#ifndef _MSC_VER
#include <unistd.h>
#else  /* _MSC_VER */
#include <io.h>
#endif  /* _MSC_VER */
#include <fcntl.h>
#include "allheaders.h"

/* --------------------------------------------*/
#if  HAVE_LIBTIFF   /* defined in environ.h */
/* --------------------------------------------*/

#include "tiff.h"
#include "tiffio.h"

static const l_int32  DefaultResolution = 300;   /* ppi */
static const l_int32  ManyPagesInTiffFile = 3000;  /* warn if big */

    /* Verified that tiflib makes valid g4 files of this size */
static const l_int32  MaxTiffWidth = 1 << 20;  /* 1M pixels */
static const l_int32  MaxTiffHeight = 1 << 20;  /* 1M pixels */

    /* Check g4 data size */
static const size_t  MaxNumTiffBytes = (1 << 28) - 1;  /* 256 MB */

    /* All functions with TIFF interfaces are static. */
static PIX      *pixReadFromTiffStream(TIFF *tif);
static l_int32   getTiffStreamResolution(TIFF *tif, l_int32 *pxres,
                                         l_int32 *pyres);
static l_int32   tiffReadHeaderTiff(TIFF *tif, l_int32 *pwidth,
                                    l_int32 *pheight, l_int32 *pbps,
                                    l_int32 *pspp, l_int32 *pres,
                                    l_int32 *pcmap, l_int32 *pformat);
static l_int32   writeCustomTiffTags(TIFF *tif, NUMA *natags,
                                     SARRAY *savals, SARRAY  *satypes,
                                     NUMA *nasizes);
static l_int32   pixWriteToTiffStream(TIFF *tif, PIX *pix, l_int32 comptype,
                                      NUMA *natags, SARRAY *savals,
                                      SARRAY *satypes, NUMA *nasizes);
static TIFF     *fopenTiff(FILE *fp, const char *modestring);
static TIFF     *openTiff(const char *filename, const char *modestring);

    /* Static helper for tiff compression type */
static l_int32   getTiffCompressedFormat(l_uint16 tiffcomp);

    /* Static function for memory I/O */
static TIFF     *fopenTiffMemstream(const char *filename, const char *operation,
                                    l_uint8 **pdata, size_t *pdatasize);

    /* This structure defines a transform to be performed on a TIFF image
     * (note that the same transformation can be represented in
     * several different ways using this structure since
     * vflip + hflip + counterclockwise == clockwise). */
struct tiff_transform {
    int vflip;    /* if non-zero, image needs a vertical fip */
    int hflip;    /* if non-zero, image needs a horizontal flip */
    int rotate;   /* -1 -> counterclockwise 90-degree rotation,
                      0 -> no rotation
                      1 -> clockwise 90-degree rotation */
};

    /* This describes the transformations needed for a given orientation
     * tag.  The tag values start at 1, so you need to subtract 1 to get a
     * valid index into this array.  It is only valid when not using
     * TIFFReadRGBAImageOriented(). */
static struct tiff_transform tiff_orientation_transforms[] = {
    {0, 0, 0},
    {0, 1, 0},
    {1, 1, 0},
    {1, 0, 0},
    {0, 1, -1},
    {0, 0, 1},
    {0, 1, 1},
    {0, 0, -1}
};

    /* Same as above, except that test transformations are only valid
     * when using TIFFReadRGBAImageOriented().  Transformations
     * were determined empirically.  See the libtiff mailing list for
     * more discussion: http://www.asmail.be/msg0054683875.html  */
static struct tiff_transform tiff_partial_orientation_transforms[] = {
    {0, 0, 0},
    {0, 0, 0},
    {0, 0, 0},
    {0, 0, 0},
    {0, 1, -1},
    {0, 1, 1},
    {1, 0, 1},
    {0, 1, -1}
};


/*-----------------------------------------------------------------------*
 *             TIFFClientOpen() wrappers for FILE*                       *
 *             Provided by Jürgen Buchmüller                             *
 *                                                                       *
 *  We previously used TIFFFdOpen(), which used low-level file           *
 *  descriptors.  It had portability issues with Windows, along          *
 *  with other limitations from lack of stream control operations.       *
 *  These callbacks to TIFFClientOpen() avoid the problems.              *
 *                                                                       *
 *  Jürgen made the functions use 64 bit file operations where possible  *
 *  or required, namely for seek and size. On Windows there are specific *
 *  _fseeki64() and _ftelli64() functions.  On unix it is common to look *
 *  for a macro _LARGEFILE64_SOURCE being defined, which makes available *
 *  the off64_t type, and to use fseeko() and ftello() in this case.     *
 *-----------------------------------------------------------------------*/
static tsize_t
lept_read_proc(thandle_t  cookie,
               tdata_t    buff,
               tsize_t    size)
{
    FILE* fp = (FILE *)cookie;
    tsize_t done;
    if (!buff || !cookie || !fp)
        return (tsize_t)-1;
    done = fread(buff, 1, size, fp);
    return done;
}

static tsize_t
lept_write_proc(thandle_t  cookie,
                tdata_t    buff,
                tsize_t    size)
{
    FILE* fp = (FILE *)cookie;
    tsize_t done;
    if (!buff || !cookie || !fp)
        return (tsize_t)-1;
    done = fwrite(buff, 1, size, fp);
    return done;
}

static toff_t
lept_seek_proc(thandle_t  cookie,
               toff_t     offs,
               int        whence)
{
    FILE* fp = (FILE *)cookie;
#if defined(_MSC_VER)
    __int64 pos = 0;
    if (!cookie || !fp)
        return (tsize_t)-1;
    switch (whence) {
    case SEEK_SET:
        pos = 0;
        break;
    case SEEK_CUR:
        pos = ftell(fp);
        break;
    case SEEK_END:
        _fseeki64(fp, 0, SEEK_END);
        pos = _ftelli64(fp);
        break;
    }
    pos = (__int64)(pos + offs);
    _fseeki64(fp, pos, SEEK_SET);
    if (pos == _ftelli64(fp))
        return (tsize_t)pos;
#elif defined(_LARGEFILE64_SOURCE)
    off64_t pos = 0;
    if (!cookie || !fp)
        return (tsize_t)-1;
    switch (whence) {
    case SEEK_SET:
        pos = 0;
        break;
    case SEEK_CUR:
        pos = ftello(fp);
        break;
    case SEEK_END:
        fseeko(fp, 0, SEEK_END);
        pos = ftello(fp);
        break;
    }
    pos = (off64_t)(pos + offs);
    fseeko(fp, pos, SEEK_SET);
    if (pos == ftello(fp))
        return (tsize_t)pos;
#else
    off_t pos = 0;
    if (!cookie || !fp)
        return (tsize_t)-1;
    switch (whence) {
    case SEEK_SET:
        pos = 0;
        break;
    case SEEK_CUR:
        pos = ftell(fp);
        break;
    case SEEK_END:
        fseek(fp, 0, SEEK_END);
        pos = ftell(fp);
        break;
    }
    pos = (off_t)(pos + offs);
    fseek(fp, pos, SEEK_SET);
    if (pos == ftell(fp))
        return (tsize_t)pos;
#endif
    return (tsize_t)-1;
}

static int
lept_close_proc(thandle_t  cookie)
{
    FILE* fp = (FILE *)cookie;
    if (!cookie || !fp)
        return 0;
    fseek(fp, 0, SEEK_SET);
    return 0;
}

static toff_t
lept_size_proc(thandle_t  cookie)
{
    FILE* fp = (FILE *)cookie;
#if defined(_MSC_VER)
    __int64 pos;
    __int64 size;
    if (!cookie || !fp)
        return (tsize_t)-1;
    pos = _ftelli64(fp);
    _fseeki64(fp, 0, SEEK_END);
    size = _ftelli64(fp);
    _fseeki64(fp, pos, SEEK_SET);
#elif defined(_LARGEFILE64_SOURCE)
    off64_t pos;
    off64_t size;
    if (!fp)
        return (tsize_t)-1;
    pos = ftello(fp);
    fseeko(fp, 0, SEEK_END);
    size = ftello(fp);
    fseeko(fp, pos, SEEK_SET);
#else
    off_t pos;
    off_t size;
    if (!cookie || !fp)
        return (tsize_t)-1;
    pos = ftell(fp);
    fseek(fp, 0, SEEK_END);
    size = ftell(fp);
    fseek(fp, pos, SEEK_SET);
#endif
    return (toff_t)size;
}


/*--------------------------------------------------------------*
 *                      Reading from file                       *
 *--------------------------------------------------------------*/
/*!
 * \brief   pixReadTiff()
 *
 * \param[in]    filename
 * \param[in]    n           page number 0 based
 * \return  pix, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) This is a version of pixRead(), specialized for tiff
 *          files, that allows specification of the page to be returned
 *      (2) No warning messages on failure, because of how multi-page
 *          TIFF reading works. You are supposed to keep trying until
 *          it stops working.
 * </pre>
 */
PIX *
pixReadTiff(const char  *filename,
            l_int32      n)
{
FILE  *fp;
PIX   *pix;

    PROCNAME("pixReadTiff");

    if (!filename)
        return (PIX *)ERROR_PTR("filename not defined", procName, NULL);

    if ((fp = fopenReadStream(filename)) == NULL)
        return (PIX *)ERROR_PTR("image file not found", procName, NULL);
    pix = pixReadStreamTiff(fp, n);
    fclose(fp);
    return pix;
}


/*--------------------------------------------------------------*
 *                     Reading from stream                      *
 *--------------------------------------------------------------*/
/*!
 * \brief   pixReadStreamTiff()
 *
 * \param[in]    fp    file stream
 * \param[in]    n     page number: 0 based
 * \return  pix, or NULL on error or if there are no more images in the file
 *
 * <pre>
 * Notes:
 *      (1) No warning messages on failure, because of how multi-page
 *          TIFF reading works. You are supposed to keep trying until
 *          it stops working.
 * </pre>
 */
PIX *
pixReadStreamTiff(FILE    *fp,
                  l_int32  n)
{
PIX   *pix;
TIFF  *tif;

    PROCNAME("pixReadStreamTiff");

    if (!fp)
        return (PIX *)ERROR_PTR("stream not defined", procName, NULL);

    if ((tif = fopenTiff(fp, "r")) == NULL)
        return (PIX *)ERROR_PTR("tif not opened", procName, NULL);

    if (TIFFSetDirectory(tif, n) == 0) {
        TIFFCleanup(tif);
        return NULL;
    }
    if ((pix = pixReadFromTiffStream(tif)) == NULL) {
        TIFFCleanup(tif);
        return NULL;
    }
    TIFFCleanup(tif);
    return pix;
}


/*!
 * \brief   pixReadFromTiffStream()
 *
 * \param[in]    tif    TIFF handle
 * \return  pix, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) We can read the following images (up to 32 bits/pixel):
 *          1 spp (grayscale): 1, 2, 4, 8, 16 bps
 *          1 spp (colormapped): 1, 2, 4, 8 bps
 *          2 spp (gray+alpha): 8 bps
 *          3 spp (rgb) and 4 spp (rgba): 8 or 16 bps
 *      (2) We do not handle 16 bps for spp == 2.
 *      (3) 2 bpp gray+alpha are rasterized as 32 bit/pixel rgba, with
 *          the gray value replicated in r, g and b.
 *      (4) For colormapped images, we support 8 bits/color in the palette.
 *          Tiff colormaps have 16 bits/color, and we reduce them to 8.
 *      (5) Quoting the libtiff documentation at
 *               http://libtiff.maptools.org/libtiff.html
 *          "libtiff provides a high-level interface for reading image data
 *          from a TIFF file. This interface handles the details of data
 *          organization and format for a wide variety of TIFF files;
 *          at least the large majority of those files that one would
 *          normally encounter. Image data is, by default, returned as
 *          ABGR pixels packed into 32-bit words (8 bits per sample).
 *          Rectangular rasters can be read or data can be intercepted
 *          at an intermediate level and packed into memory in a format
 *          more suitable to the application. The library handles all
 *          the details of the format of data stored on disk and,
 *          in most cases, if any colorspace conversions are required:
 *          bilevel to RGB, greyscale to RGB, CMYK to RGB, YCbCr to RGB,
 *          16-bit samples to 8-bit samples, associated/unassociated alpha,
 *          etc."
 * </pre>
 */
static PIX *
pixReadFromTiffStream(TIFF  *tif)
{
char      *text;
l_uint8   *linebuf, *data, *rowptr;
l_uint16   spp, bps, photometry, tiffcomp, orientation, sample_fmt;
l_uint16  *redmap, *greenmap, *bluemap;
l_int32    d, wpl, bpl, comptype, i, j, k, ncolors, rval, gval, bval, aval;
l_int32    xres, yres, tiffbpl, packedbpl, halfsize;
l_uint32   w, h, tiffword, read_oriented;
l_uint32  *line, *ppixel, *tiffdata, *pixdata;
PIX       *pix, *pix1;
PIXCMAP   *cmap;

    PROCNAME("pixReadFromTiffStream");

    if (!tif)
        return (PIX *)ERROR_PTR("tif not defined", procName, NULL);

    read_oriented = 0;

        /* Only accept uint image data:
         *   SAMPLEFORMAT_UINT = 1;
         *   SAMPLEFORMAT_INT = 2;
         *   SAMPLEFORMAT_IEEEFP = 3;
         *   SAMPLEFORMAT_VOID = 4;   */
    TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLEFORMAT, &sample_fmt);
    if (sample_fmt != SAMPLEFORMAT_UINT) {
        L_ERROR("sample format = %d is not uint\n", procName, sample_fmt);
        return NULL;
    }

        /* Can't read tiff in tiled format. For what is involved, see, e.g:
         *   https://www.cs.rochester.edu/~nelson/courses/vision/\
         *     resources/tiff/libtiff.html#Tiles
         * A tiled tiff can be converted to a normal (strip) tif:
         *   tiffcp -s <input-tiled-tif> <output-strip-tif>    */
    if (TIFFIsTiled(tif)) {
        L_ERROR("tiled format is not supported\n", procName);
        return NULL;
    }

        /* Old style jpeg is not supported.  We tried supporting 8 bpp.
         * TIFFReadScanline() fails on this format, so we used RGBA
         * reading, which generates a 4 spp image, and pulled out the
         * red component.  However, there were problems with double-frees
         * in cleanup.  For RGB, tiffbpl is exactly half the size that
         * you would expect for the raster data in a scanline, which
         * is 3 * w.  */
    TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &tiffcomp);
    if (tiffcomp == COMPRESSION_OJPEG) {
        L_ERROR("old style jpeg format is not supported\n", procName);
        return NULL;
    }

        /* webp in tiff is in 4.1.0 and not yet supported in Adobe registry */
#if defined(COMPRESSION_WEBP)
    if (tiffcomp == COMPRESSION_WEBP) {
        L_ERROR("webp in tiff not generally supported yet\n", procName);
        return NULL;
    }
#endif  /* COMPRESSION_WEBP */

        /* Use default fields for bps and spp */
    TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bps);
    TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &spp);
    if (bps != 1 && bps != 2 && bps != 4 && bps != 8 && bps != 16) {
        L_ERROR("invalid bps = %d\n", procName, bps);
        return NULL;
    }
    if (spp == 2 && bps != 8) {
        L_WARNING("for 2 spp, only handle 8 bps\n", procName);
        return NULL;
    }
    if (spp == 1)
        d = bps;
    else if (spp == 2)  /* gray plus alpha */
        d = 32;  /* will convert to RGBA */
    else if (spp == 3 || spp == 4)
        d = 32;
    else
        return (PIX *)ERROR_PTR("spp not in set {1,2,3,4}", procName, NULL);

    TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
    TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
    if (w > MaxTiffWidth) {
        L_ERROR("width = %d pixels; too large\n", procName, w);
        return NULL;
    }
    if (h > MaxTiffHeight) {
        L_ERROR("height = %d pixels; too large\n", procName, h);
        return NULL;
    }

        /* The relation between the size of a byte buffer required to hold
           a raster of image pixels (packedbpl) and the size of the tiff
           buffer (tiffbuf) is either 1:1 or approximately 2:1, depending
           on how the data is stored and subsampled.  Allow some slop
           when validating the relation between buffer size and the image
           parameters w, spp and bps. */
    tiffbpl = TIFFScanlineSize(tif);
    packedbpl = (bps * spp * w + 7) / 8;
    halfsize = L_ABS(2 * tiffbpl - packedbpl) <= 8;
#if 0
    if (halfsize)
        L_INFO("packedbpl = %d is approx. twice tiffbpl = %d\n", procName,
               packedbpl, tiffbpl);
#endif
    if (tiffbpl != packedbpl && !halfsize) {
        L_ERROR("invalid tiffbpl: tiffbpl = %d, packedbpl = %d, "
                "bps = %d, spp = %d, w = %d\n",
                procName, tiffbpl, packedbpl, bps, spp, w);
        return NULL;
    }

    if ((pix = pixCreate(w, h, d)) == NULL)
        return (PIX *)ERROR_PTR("pix not made", procName, NULL);
    pixSetInputFormat(pix, IFF_TIFF);
    data = (l_uint8 *)pixGetData(pix);
    wpl = pixGetWpl(pix);
    bpl = 4 * wpl;

    if (spp == 1) {
        linebuf = (l_uint8 *)LEPT_CALLOC(tiffbpl + 1, sizeof(l_uint8));
        for (i = 0; i < h; i++) {
            if (TIFFReadScanline(tif, linebuf, i, 0) < 0) {
                LEPT_FREE(linebuf);
                pixDestroy(&pix);
                return (PIX *)ERROR_PTR("line read fail", procName, NULL);
            }
            memcpy(data, linebuf, tiffbpl);
            data += bpl;
        }
        if (bps <= 8)
            pixEndianByteSwap(pix);
        else   /* bps == 16 */
            pixEndianTwoByteSwap(pix);
        LEPT_FREE(linebuf);
    } else if (spp == 2 && bps == 8) {  /* gray plus alpha */
        L_INFO("gray+alpha is not supported; converting to RGBA\n", procName);
        pixSetSpp(pix, 4);
        linebuf = (l_uint8 *)LEPT_CALLOC(2 * tiffbpl + 1, sizeof(l_uint8));
        pixdata = pixGetData(pix);
        for (i = 0; i < h; i++) {
            if (TIFFReadScanline(tif, linebuf, i, 0) < 0) {
                LEPT_FREE(linebuf);
                pixDestroy(&pix);
                return (PIX *)ERROR_PTR("line read fail", procName, NULL);
            }
            rowptr = linebuf;
            ppixel = pixdata + i * wpl;
            for (j = k = 0; j < w; j++) {
                    /* Copy gray value into r, g and b */
                SET_DATA_BYTE(ppixel, COLOR_RED, rowptr[k]);
                SET_DATA_BYTE(ppixel, COLOR_GREEN, rowptr[k]);
                SET_DATA_BYTE(ppixel, COLOR_BLUE, rowptr[k++]);
                SET_DATA_BYTE(ppixel, L_ALPHA_CHANNEL, rowptr[k++]);
                ppixel++;
            }
        }
        LEPT_FREE(linebuf);
    } else {  /* rgb and rgba */
        if ((tiffdata = (l_uint32 *)LEPT_CALLOC((size_t)w * h,
                                                 sizeof(l_uint32))) == NULL) {
            pixDestroy(&pix);
            return (PIX *)ERROR_PTR("calloc fail for tiffdata", procName, NULL);
        }
            /* TIFFReadRGBAImageOriented() converts to 8 bps */
        if (!TIFFReadRGBAImageOriented(tif, w, h, tiffdata,
                                       ORIENTATION_TOPLEFT, 0)) {
            LEPT_FREE(tiffdata);
            pixDestroy(&pix);
            return (PIX *)ERROR_PTR("failed to read tiffdata", procName, NULL);
        } else {
            read_oriented = 1;
        }

        if (spp == 4) pixSetSpp(pix, 4);
        line = pixGetData(pix);
        for (i = 0; i < h; i++, line += wpl) {
            for (j = 0, ppixel = line; j < w; j++) {
                    /* TIFFGet* are macros */
                tiffword = tiffdata[i * w + j];
                rval = TIFFGetR(tiffword);
                gval = TIFFGetG(tiffword);
                bval = TIFFGetB(tiffword);
                if (spp == 3) {
                    composeRGBPixel(rval, gval, bval, ppixel);
                } else {  /* spp == 4 */
                    aval = TIFFGetA(tiffword);
                    composeRGBAPixel(rval, gval, bval, aval, ppixel);
                }
                ppixel++;
            }
        }
        LEPT_FREE(tiffdata);
    }

    if (getTiffStreamResolution(tif, &xres, &yres) == 0) {
        pixSetXRes(pix, xres);
        pixSetYRes(pix, yres);
    }

        /* Find and save the compression type */
    comptype = getTiffCompressedFormat(tiffcomp);
    pixSetInputFormat(pix, comptype);

    if (TIFFGetField(tif, TIFFTAG_COLORMAP, &redmap, &greenmap, &bluemap)) {
            /* Save the colormap as a pix cmap.  Because the
             * tiff colormap components are 16 bit unsigned,
             * and go from black (0) to white (0xffff), the
             * the pix cmap takes the most significant byte. */
        if (bps > 8) {
            pixDestroy(&pix);
            return (PIX *)ERROR_PTR("colormap size > 256", procName, NULL);
        }
        if ((cmap = pixcmapCreate(bps)) == NULL) {
            pixDestroy(&pix);
            return (PIX *)ERROR_PTR("colormap not made", procName, NULL);
        }
        ncolors = 1 << bps;
        for (i = 0; i < ncolors; i++)
            pixcmapAddColor(cmap, redmap[i] >> 8, greenmap[i] >> 8,
                            bluemap[i] >> 8);
        if (pixSetColormap(pix, cmap)) {
            pixDestroy(&pix);
            return (PIX *)ERROR_PTR("invalid colormap", procName, NULL);
        }

            /* Remove the colormap for 1 bpp. */
        if (bps == 1) {
            pix1 = pixRemoveColormap(pix, REMOVE_CMAP_BASED_ON_SRC);
            pixDestroy(&pix);
            pix = pix1;
        }
    } else {   /* No colormap: check photometry and invert if necessary */
        if (!TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &photometry)) {
                /* Guess default photometry setting.  Assume min_is_white
                 * if compressed 1 bpp; min_is_black otherwise. */
            if (tiffcomp == COMPRESSION_CCITTFAX3 ||
                tiffcomp == COMPRESSION_CCITTFAX4 ||
                tiffcomp == COMPRESSION_CCITTRLE ||
                tiffcomp == COMPRESSION_CCITTRLEW) {
                photometry = PHOTOMETRIC_MINISWHITE;
            } else {
                photometry = PHOTOMETRIC_MINISBLACK;
            }
        }
        if ((d == 1 && photometry == PHOTOMETRIC_MINISBLACK) ||
            (d == 8 && photometry == PHOTOMETRIC_MINISWHITE))
            pixInvert(pix, pix);
    }

    if (TIFFGetField(tif, TIFFTAG_ORIENTATION, &orientation)) {
        if (orientation >= 1 && orientation <= 8) {
            struct tiff_transform *transform = (read_oriented) ?
                &tiff_partial_orientation_transforms[orientation - 1] :
                &tiff_orientation_transforms[orientation - 1];
            if (transform->vflip) pixFlipTB(pix, pix);
            if (transform->hflip) pixFlipLR(pix, pix);
            if (transform->rotate) {
                PIX *oldpix = pix;
                pix = pixRotate90(oldpix, transform->rotate);
                pixDestroy(&oldpix);
            }
        }
    }

    text = NULL;
    TIFFGetField(tif, TIFFTAG_IMAGEDESCRIPTION, &text);
    if (text) pixSetText(pix, text);
    return pix;
}


/*--------------------------------------------------------------*
 *                       Writing to file                        *
 *--------------------------------------------------------------*/
/*!
 * \brief   pixWriteTiff()
 *
 * \param[in]    filename   to write to
 * \param[in]    pix        any depth, colormap will be removed
 * \param[in]    comptype   IFF_TIFF, IFF_TIFF_RLE, IFF_TIFF_PACKBITS,
 *                          IFF_TIFF_G3, IFF_TIFF_G4,
 *                          IFF_TIFF_LZW, IFF_TIFF_ZIP, IFF_TIFF_JPEG
 * \param[in]    modestr    "a" or "w"
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) For multipage tiff, write the first pix with mode "w" and
 *          all subsequent pix with mode "a".
 *      (2) For multipage tiff, there is considerable overhead in the
 *          machinery to append an image and add the directory entry,
 *          and the time required for each image increases linearly
 *          with the number of images in the file.
 * </pre>
 */
l_ok
pixWriteTiff(const char  *filename,
             PIX         *pix,
             l_int32      comptype,
             const char  *modestr)
{
    return pixWriteTiffCustom(filename, pix, comptype, modestr,
                              NULL, NULL, NULL, NULL);
}


/*!
 * \brief   pixWriteTiffCustom()
 *
 * \param[in]    filename   to write to
 * \param[in]    pix
 * \param[in]    comptype   IFF_TIFF, IFF_TIFF_RLE, IFF_TIFF_PACKBITS,
 *                          IFF_TIFF_G3, IFF_TIFF_G4,
 *                          IFF_TIFF_LZW, IFF_TIFF_ZIP, IFF_TIFF_JPEG
 * \param[in]    modestr    "a" or "w"
 * \param[in]    natags [optional] NUMA of custom tiff tags
 * \param[in]    savals [optional] SARRAY of values
 * \param[in]    satypes [optional] SARRAY of types
 * \param[in]    nasizes [optional] NUMA of sizes
 * \return  0 if OK, 1 on error
 *
 *  Usage:
 *      1 This writes a page image to a tiff file, with optional
 *          extra tags defined in tiff.h
 *      2 For multipage tiff, write the first pix with mode "w" and
 *          all subsequent pix with mode "a".
 *      3 For the custom tiff tags:
 *          a The three arrays {natags, savals, satypes} must all be
 *              either NULL or defined and of equal size.
 *          b If they are defined, the tags are an array of integers,
 *              the vals are an array of values in string format, and
 *              the types are an array of types in string format.
 *          c All valid tags are definined in tiff.h.
 *          d The types allowed are the set of strings:
 *                "char*"
 *                "l_uint8*"
 *                "l_uint16"
 *                "l_uint32"
 *                "l_int32"
 *                "l_float64"
 *                "l_uint16-l_uint16" note the dash; use it between the
 *                                    two l_uint16 vals in the val string
 *              Of these, "char*" and "l_uint16" are the most commonly used.
 *          e The last array, nasizes, is also optional.  It is for
 *              tags that take an array of bytes for a value, a number of
 *              elements in the array, and a type that is either "char*"
 *              or "l_uint8*" probably either will work.
 *              Use NULL if there are no such tags.
 *          f VERY IMPORTANT: if there are any tags that require the
 *              extra size value, stored in nasizes, they must be
 *              written first!
 */
l_ok
pixWriteTiffCustom(const char  *filename,
                   PIX         *pix,
                   l_int32      comptype,
                   const char  *modestr,
                   NUMA        *natags,
                   SARRAY      *savals,
                   SARRAY      *satypes,
                   NUMA        *nasizes)
{
l_int32  ret;
TIFF    *tif;

    PROCNAME("pixWriteTiffCustom");

    if (!filename)
        return ERROR_INT("filename not defined", procName, 1);
    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);

    if ((tif = openTiff(filename, modestr)) == NULL)
        return ERROR_INT("tif not opened", procName, 1);
    ret = pixWriteToTiffStream(tif, pix, comptype, natags, savals,
                               satypes, nasizes);
    TIFFClose(tif);
    return ret;
}


/*--------------------------------------------------------------*
 *                       Writing to stream                      *
 *--------------------------------------------------------------*/
/*!
 * \brief   pixWriteStreamTiff()
 *
 * \param[in]    fp       file stream
 * \param[in]    pix
 * \param[in]    comptype IFF_TIFF, IFF_TIFF_RLE, IFF_TIFF_PACKBITS,
 *                        IFF_TIFF_G3, IFF_TIFF_G4,
 *                        IFF_TIFF_LZW, IFF_TIFF_ZIP, IFF_TIFF_JPEG
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This writes a single image to a file stream opened for writing.
 *      (2) If the pix has a colormap, it is preserved in the output file.
 *      (3) For images with bpp > 1, this resets the comptype, if
 *          necessary, to write uncompressed data.
 *      (4) G3 and G4 are only defined for 1 bpp.
 *      (5) We only allow PACKBITS for bpp = 1, because for bpp > 1
 *          it typically expands images that are not synthetically generated.
 *      (6) G4 compression is typically about twice as good as G3.
 *          G4 is excellent for binary compression of text/line-art,
 *          but terrible for halftones and dithered patterns.  (In
 *          fact, G4 on halftones can give a file that is larger
 *          than uncompressed!)  If a binary image has dithered
 *          regions, it is usually better to compress with png.
 * </pre>
 */
l_ok
pixWriteStreamTiff(FILE    *fp,
                   PIX     *pix,
                   l_int32  comptype)
{
    return pixWriteStreamTiffWA(fp, pix, comptype, "w");
}


/*!
 * \brief   pixWriteStreamTiffWA()
 *
 * \param[in]    fp       file stream opened for append or write
 * \param[in]    pix
 * \param[in]    comptype IFF_TIFF, IFF_TIFF_RLE, IFF_TIFF_PACKBITS,
 *                        IFF_TIFF_G3, IFF_TIFF_G4,
 *                        IFF_TIFF_LZW, IFF_TIFF_ZIP, IFF_TIFF_JPEG
 * \param[in]    modestr  "w" or "a"
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) See pixWriteStreamTiff()
 * </pre>
 */
l_ok
pixWriteStreamTiffWA(FILE        *fp,
                     PIX         *pix,
                     l_int32      comptype,
                     const char  *modestr)
{
TIFF  *tif;

    PROCNAME("pixWriteStreamTiffWA");

    if (!fp)
        return ERROR_INT("stream not defined", procName, 1 );
    if (!pix)
        return ERROR_INT("pix not defined", procName, 1 );
    if (strcmp(modestr, "w") && strcmp(modestr, "a"))
        return ERROR_INT("modestr not 'w' or 'a'", procName, 1 );

    if (pixGetDepth(pix) != 1 && comptype != IFF_TIFF &&
        comptype != IFF_TIFF_LZW && comptype != IFF_TIFF_ZIP &&
        comptype != IFF_TIFF_JPEG) {
        L_WARNING("invalid compression type for bpp > 1\n", procName);
        comptype = IFF_TIFF_ZIP;
    }

    if ((tif = fopenTiff(fp, modestr)) == NULL)
        return ERROR_INT("tif not opened", procName, 1);

    if (pixWriteToTiffStream(tif, pix, comptype, NULL, NULL, NULL, NULL)) {
        TIFFCleanup(tif);
        return ERROR_INT("tif write error", procName, 1);
    }

    TIFFCleanup(tif);
    return 0;
}


/*!
 * \brief   pixWriteToTiffStream()
 *
 * \param[in]    tif       data structure, opened to a file
 * \param[in]    pix
 * \param[in]    comptype  IFF_TIFF: for any image; no compression
 *                         IFF_TIFF_RLE, IFF_TIFF_PACKBITS: for 1 bpp only
 *                         IFF_TIFF_G4 and IFF_TIFF_G3: for 1 bpp only
 *                         IFF_TIFF_LZW, IFF_TIFF_ZIP: lossless for any image
 *                         IFF_TIFF_JPEG: lossy 8 bpp gray or rgb
 * \param[in]    natags    [optional] NUMA of custom tiff tags
 * \param[in]    savals    [optional] SARRAY of values
 * \param[in]    satypes   [optional] SARRAY of types
 * \param[in]    nasizes   [optional] NUMA of sizes
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This static function should only be called through higher
 *          level functions in this file; namely, pixWriteTiffCustom(),
 *          pixWriteTiff(), pixWriteStreamTiff(), pixWriteMemTiff()
 *          and pixWriteMemTiffCustom().
 *      (2) We only allow PACKBITS for bpp = 1, because for bpp > 1
 *          it typically expands images that are not synthetically generated.
 *      (3) See pixWriteTiffCustom() for details on how to use
 *          the last four parameters for customized tiff tags.
 *      (4) The only valid pixel depths in leptonica are 1, 2, 4, 8, 16
 *          and 32.  However, it is possible, and in some cases desirable,
 *          to write out a tiff file using an rgb pix that has 24 bpp.
 *          This can be created by appending the raster data for a 24 bpp
 *          image (with proper scanline padding) directly to a 24 bpp
 *          pix that was created without a data array.  See note in
 *          pixWriteStreamPng() for an example.
 * </pre>
 */
static l_int32
pixWriteToTiffStream(TIFF    *tif,
                     PIX     *pix,
                     l_int32  comptype,
                     NUMA    *natags,
                     SARRAY  *savals,
                     SARRAY  *satypes,
                     NUMA    *nasizes)
{
l_uint8   *linebuf, *data;
l_uint16   redmap[256], greenmap[256], bluemap[256];
l_int32    w, h, d, spp, i, j, k, wpl, bpl, tiffbpl, ncolors, cmapsize;
l_int32   *rmap, *gmap, *bmap;
l_int32    xres, yres;
l_uint32  *line, *ppixel;
PIX       *pixt;
PIXCMAP   *cmap;
char      *text;

    PROCNAME("pixWriteToTiffStream");

    if (!tif)
        return ERROR_INT("tif stream not defined", procName, 1);
    if (!pix)
        return ERROR_INT( "pix not defined", procName, 1 );

    pixSetPadBits(pix, 0);
    pixGetDimensions(pix, &w, &h, &d);
    spp = pixGetSpp(pix);
    xres = pixGetXRes(pix);
    yres = pixGetYRes(pix);
    if (xres == 0) xres = DefaultResolution;
    if (yres == 0) yres = DefaultResolution;

        /* ------------------ Write out the header -------------  */
    TIFFSetField(tif, TIFFTAG_RESOLUTIONUNIT, (l_uint32)RESUNIT_INCH);
    TIFFSetField(tif, TIFFTAG_XRESOLUTION, (l_float64)xres);
    TIFFSetField(tif, TIFFTAG_YRESOLUTION, (l_float64)yres);

    TIFFSetField(tif, TIFFTAG_IMAGEWIDTH, (l_uint32)w);
    TIFFSetField(tif, TIFFTAG_IMAGELENGTH, (l_uint32)h);
    TIFFSetField(tif, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT);

    if ((text = pixGetText(pix)) != NULL)
        TIFFSetField(tif, TIFFTAG_IMAGEDESCRIPTION, text);

    if (d == 1 && !pixGetColormap(pix)) {
            /* If d == 1, preserve the colormap.  Note that when
             * d == 1 pix with colormaps are read, the colormaps
             * are removed.  The only pix in leptonica that have
             * colormaps are made programmatically. */
        TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISWHITE);
    } else if ((d == 32 && spp == 3) || d == 24) {
        TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
        TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, (l_uint16)3);
        TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE,
                       (l_uint16)8, (l_uint16)8, (l_uint16)8);
    } else if (d == 32 && spp == 4) {
        l_uint16  val[1];
        val[0] = EXTRASAMPLE_ASSOCALPHA;
        TIFFSetField(tif, TIFFTAG_EXTRASAMPLES, (l_uint16)1, &val);
        TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB);
        TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, (l_uint16)4);
        TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE,
                     (l_uint16)8, (l_uint16)8, (l_uint16)8, (l_uint16)8);
    } else if (d == 16) {  /* we only support spp = 1, bps = 16 */
        TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
    } else if ((cmap = pixGetColormap(pix)) == NULL) {
        TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_MINISBLACK);
    } else {  /* Save colormap in the tiff; not more than 256 colors */
        if (d > 8) {
            L_ERROR("d = %d > 8 with colormap!; reducing to 8\n", procName, d);
            d = 8;
        }
        pixcmapToArrays(cmap, &rmap, &gmap, &bmap, NULL);
        ncolors = pixcmapGetCount(cmap);
        ncolors = L_MIN(256, ncolors);  /* max 256 */
        cmapsize = 1 << d;
        cmapsize = L_MIN(256, cmapsize);  /* power of 2; max 256 */
        if (ncolors > cmapsize) {
            L_WARNING("too many colors in cmap for tiff; truncating\n",
                      procName);
            ncolors = cmapsize;
        }
        for (i = 0; i < ncolors; i++) {
            redmap[i] = (rmap[i] << 8) | rmap[i];
            greenmap[i] = (gmap[i] << 8) | gmap[i];
            bluemap[i] = (bmap[i] << 8) | bmap[i];
        }
        for (i = ncolors; i < cmapsize; i++)  /* init, even though not used */
            redmap[i] = greenmap[i] = bluemap[i] = 0;
        LEPT_FREE(rmap);
        LEPT_FREE(gmap);
        LEPT_FREE(bmap);

        TIFFSetField(tif, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE);
        TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, (l_uint16)1);
        TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, (l_uint16)d);
        TIFFSetField(tif, TIFFTAG_COLORMAP, redmap, greenmap, bluemap);
    }

    if (d <= 16) {
        TIFFSetField(tif, TIFFTAG_BITSPERSAMPLE, (l_uint16)d);
        TIFFSetField(tif, TIFFTAG_SAMPLESPERPIXEL, (l_uint16)1);
    }

    TIFFSetField(tif, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
    if (comptype == IFF_TIFF) {  /* no compression */
        TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
    } else if (comptype == IFF_TIFF_G4) {
        TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX4);
    } else if (comptype == IFF_TIFF_G3) {
        TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_CCITTFAX3);
    } else if (comptype == IFF_TIFF_RLE) {
        TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_CCITTRLE);
    } else if (comptype == IFF_TIFF_PACKBITS) {
        TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_PACKBITS);
    } else if (comptype == IFF_TIFF_LZW) {
        TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_LZW);
    } else if (comptype == IFF_TIFF_ZIP) {
        TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_ADOBE_DEFLATE);
    } else if (comptype == IFF_TIFF_JPEG) {
        TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_JPEG);
    } else {
        L_WARNING("unknown tiff compression; using none\n", procName);
        TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
    }

        /* This is a no-op if arrays are NULL */
    writeCustomTiffTags(tif, natags, savals, satypes, nasizes);

        /* ------------- Write out the image data -------------  */
    tiffbpl = TIFFScanlineSize(tif);
    wpl = pixGetWpl(pix);
    bpl = 4 * wpl;
    if (tiffbpl > bpl)
        lept_stderr("Big trouble: tiffbpl = %d, bpl = %d\n", tiffbpl, bpl);
    if ((linebuf = (l_uint8 *)LEPT_CALLOC(1, bpl)) == NULL)
        return ERROR_INT("calloc fail for linebuf", procName, 1);

        /* Use single strip for image */
    TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, h);

    if (d != 24 && d != 32) {
        if (d == 16)
            pixt = pixEndianTwoByteSwapNew(pix);
        else
            pixt = pixEndianByteSwapNew(pix);
        data = (l_uint8 *)pixGetData(pixt);
        for (i = 0; i < h; i++, data += bpl) {
            memcpy(linebuf, data, tiffbpl);
            if (TIFFWriteScanline(tif, linebuf, i, 0) < 0)
                break;
        }
        pixDestroy(&pixt);
    } else if (d == 24) {  /* See note 4 above: special case of 24 bpp rgb */
        for (i = 0; i < h; i++) {
            line = pixGetData(pix) + i * wpl;
            if (TIFFWriteScanline(tif, (l_uint8 *)line, i, 0) < 0)
                break;
        }
    } else {  /* 32 bpp rgb or rgba */
        for (i = 0; i < h; i++) {
            line = pixGetData(pix) + i * wpl;
            for (j = 0, k = 0, ppixel = line; j < w; j++) {
                linebuf[k++] = GET_DATA_BYTE(ppixel, COLOR_RED);
                linebuf[k++] = GET_DATA_BYTE(ppixel, COLOR_GREEN);
                linebuf[k++] = GET_DATA_BYTE(ppixel, COLOR_BLUE);
                if (spp == 4)
                    linebuf[k++] = GET_DATA_BYTE(ppixel, L_ALPHA_CHANNEL);
                ppixel++;
            }
            if (TIFFWriteScanline(tif, linebuf, i, 0) < 0)
                break;
        }
    }

/*    TIFFWriteDirectory(tif); */
    LEPT_FREE(linebuf);

    return 0;
}


/*!
 * \brief   writeCustomTiffTags()
 *
 * \param[in]    tif
 * \param[in]    natags   [optional] NUMA of custom tiff tags
 * \param[in]    savals   [optional] SARRAY of values
 * \param[in]    satypes  [optional] SARRAY of types
 * \param[in]    nasizes  [optional] NUMA of sizes
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This static function should be called indirectly through
 *          higher level functions, such as pixWriteTiffCustom(),
 *          which call pixWriteToTiffStream().  See details in
 *          pixWriteTiffCustom() for using the 4 input arrays.
 *      (2) This is a no-op if the first 3 arrays are all NULL.
 *      (3) Otherwise, the first 3 arrays must be defined and all
 *          of equal size.
 *      (4) The fourth array is always optional.
 *      (5) The most commonly used types are "char*" and "u_int16".
 *          See tiff.h for a full listing of the tiff tags.
 *          Note that many of these tags, in particular the bit tags,
 *          are intended to be private, and cannot be set by this function.
 *          Examples are the STRIPOFFSETS and STRIPBYTECOUNTS tags,
 *          which are bit tags that are automatically set in the header,
 *          and can be extracted using tiffdump.
 * </pre>
 */
static l_int32
writeCustomTiffTags(TIFF    *tif,
                    NUMA    *natags,
                    SARRAY  *savals,
                    SARRAY  *satypes,
                    NUMA    *nasizes)
{
char      *sval, *type;
l_int32    i, n, ns, size, tagval, val;
l_float64  dval;
l_uint32   uval, uval2;

    PROCNAME("writeCustomTiffTags");

    if (!tif)
        return ERROR_INT("tif stream not defined", procName, 1);
    if (!natags && !savals && !satypes)
        return 0;
    if (!natags || !savals || !satypes)
        return ERROR_INT("not all arrays defined", procName, 1);
    n = numaGetCount(natags);
    if ((sarrayGetCount(savals) != n) || (sarrayGetCount(satypes) != n))
        return ERROR_INT("not all sa the same size", procName, 1);

        /* The sized arrays (4 args to TIFFSetField) are written first */
    if (nasizes) {
        ns = numaGetCount(nasizes);
        if (ns > n)
            return ERROR_INT("too many 4-arg tag calls", procName, 1);
        for (i = 0; i < ns; i++) {
            numaGetIValue(natags, i, &tagval);
            sval = sarrayGetString(savals, i, L_NOCOPY);
            type = sarrayGetString(satypes, i, L_NOCOPY);
            numaGetIValue(nasizes, i, &size);
            if (strcmp(type, "char*") && strcmp(type, "l_uint8*"))
                L_WARNING("array type not char* or l_uint8*; ignore\n",
                          procName);
            TIFFSetField(tif, tagval, size, sval);
        }
    } else {
        ns = 0;
    }

        /* The typical tags (3 args to TIFFSetField) are now written */
    for (i = ns; i < n; i++) {
        numaGetIValue(natags, i, &tagval);
        sval = sarrayGetString(savals, i, L_NOCOPY);
        type = sarrayGetString(satypes, i, L_NOCOPY);
        if (!strcmp(type, "char*") || !strcmp(type, "const char*")) {
            TIFFSetField(tif, tagval, sval);
        } else if (!strcmp(type, "l_uint16")) {
            if (sscanf(sval, "%u", &uval) == 1) {
                TIFFSetField(tif, tagval, (l_uint16)uval);
            } else {
                lept_stderr("val %s not of type %s\n", sval, type);
                return ERROR_INT("custom tag(s) not written", procName, 1);
            }
        } else if (!strcmp(type, "l_uint32")) {
            if (sscanf(sval, "%u", &uval) == 1) {
                TIFFSetField(tif, tagval, uval);
            } else {
                lept_stderr("val %s not of type %s\n", sval, type);
                return ERROR_INT("custom tag(s) not written", procName, 1);
            }
        } else if (!strcmp(type, "l_int32")) {
            if (sscanf(sval, "%d", &val) == 1) {
                TIFFSetField(tif, tagval, val);
            } else {
                lept_stderr("val %s not of type %s\n", sval, type);
                return ERROR_INT("custom tag(s) not written", procName, 1);
            }
        } else if (!strcmp(type, "l_float64")) {
            if (sscanf(sval, "%lf", &dval) == 1) {
                TIFFSetField(tif, tagval, dval);
            } else {
                lept_stderr("val %s not of type %s\n", sval, type);
                return ERROR_INT("custom tag(s) not written", procName, 1);
            }
        } else if (!strcmp(type, "l_uint16-l_uint16")) {
            if (sscanf(sval, "%u-%u", &uval, &uval2) == 2) {
                TIFFSetField(tif, tagval, (l_uint16)uval, (l_uint16)uval2);
            } else {
                lept_stderr("val %s not of type %s\n", sval, type);
                return ERROR_INT("custom tag(s) not written", procName, 1);
            }
        } else {
            lept_stderr("unknown type %s\n",type);
            return ERROR_INT("unknown type; tag(s) not written", procName, 1);
        }
    }
    return 0;
}


/*--------------------------------------------------------------*
 *               Reading and writing multipage tiff             *
 *--------------------------------------------------------------*/
/*!
 * \brief   pixReadFromMultipageTiff()
 *
 * \param[in]      fname     filename
 * \param[in,out]  poffset   set offset to 0 for first image
 * \return  pix, or NULL on error or if previous call returned the last image
 *
 * <pre>
 * Notes:
 *      (1) This allows overhead for traversal of a multipage tiff file
 *          to be linear in the number of images.  This will also work
 *          with a singlepage tiff file.
 *      (2) No TIFF internal data structures are exposed to the caller
 *          (thanks to Jeff Breidenbach).
 *      (3) offset is the byte offset of a particular image in a multipage
 *          tiff file. To get the first image in the file, input the
 *          special offset value of 0.
 *      (4) The offset is updated to point to the next image, for a
 *          subsequent call.
 *      (5) On the last image, the offset returned is 0.  Exit the loop
 *          when the returned offset is 0.
 *      (6) For reading a multipage tiff from a memory buffer, see
 *            pixReadMemFromMultipageTiff()
 *      (7) Example usage for reading all the images in the tif file:
 *            size_t offset = 0;
 *            do {
 *                Pix *pix = pixReadFromMultipageTiff(filename, &offset);
 *                // do something with pix
 *            } while (offset != 0);
 * </pre>
 */
PIX *
pixReadFromMultipageTiff(const char  *fname,
                         size_t      *poffset)
{
l_int32  retval;
size_t   offset;
PIX     *pix;
TIFF    *tif;

    PROCNAME("pixReadFromMultipageTiff");

    if (!fname)
        return (PIX *)ERROR_PTR("fname not defined", procName, NULL);
    if (!poffset)
        return (PIX *)ERROR_PTR("&offset not defined", procName, NULL);

    if ((tif = openTiff(fname, "r")) == NULL) {
        L_ERROR("tif open failed for %s\n", procName, fname);
        return NULL;
    }

        /* Set ptrs in the TIFF to the beginning of the image */
    offset = *poffset;
    retval = (offset == 0) ? TIFFSetDirectory(tif, 0)
                            : TIFFSetSubDirectory(tif, offset);
    if (retval == 0) {
        TIFFCleanup(tif);
        return NULL;
    }

    if ((pix = pixReadFromTiffStream(tif)) == NULL) {
        TIFFCleanup(tif);
        return NULL;
    }

        /* Advance to the next image and return the new offset */
    TIFFReadDirectory(tif);
    *poffset = TIFFCurrentDirOffset(tif);
    TIFFClose(tif);
    return pix;
}


/*!
 * \brief   pixaReadMultipageTiff()
 *
 * \param[in]    filename    input tiff file
 * \return  pixa of page images, or NULL on error
 */
PIXA *
pixaReadMultipageTiff(const char  *filename)
{
l_int32  i, npages;
FILE    *fp;
PIX     *pix;
PIXA    *pixa;
TIFF    *tif;

    PROCNAME("pixaReadMultipageTiff");

    if (!filename)
        return (PIXA *)ERROR_PTR("filename not defined", procName, NULL);

    if ((fp = fopenReadStream(filename)) == NULL)
        return (PIXA *)ERROR_PTR("stream not opened", procName, NULL);
    if (fileFormatIsTiff(fp)) {
        tiffGetCount(fp, &npages);
        L_INFO(" Tiff: %d pages\n", procName, npages);
    } else {
        return (PIXA *)ERROR_PTR("file not tiff", procName, NULL);
    }

    if ((tif = fopenTiff(fp, "r")) == NULL)
        return (PIXA *)ERROR_PTR("tif not opened", procName, NULL);

    pixa = pixaCreate(npages);
    pix = NULL;
    for (i = 0; i < npages; i++) {
        if ((pix = pixReadFromTiffStream(tif)) != NULL) {
            pixaAddPix(pixa, pix, L_INSERT);
        } else {
            L_WARNING("pix not read for page %d\n", procName, i);
        }

            /* Advance to the next directory (i.e., the next image) */
        if (TIFFReadDirectory(tif) == 0)
            break;
    }

    fclose(fp);
    TIFFCleanup(tif);
    return pixa;
}


/*!
 * \brief   pixaWriteMultipageTiff()
 *
 * \param[in]    fname      input tiff file
 * \param[in]    pixa       any depth; colormap will be removed
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) The tiff directory overhead is O(n^2).  I have not been
 *          able to reduce it to O(n).  The overhead for n = 2000 is
 *          about 1 second.
 * </pre>
 */
l_ok
pixaWriteMultipageTiff(const char  *fname,
                       PIXA        *pixa)
{
const char  *modestr;
l_int32      i, n;
PIX         *pix1;

    PROCNAME("pixaWriteMultipageTiff");

    if (!fname)
        return ERROR_INT("fname not defined", procName, 1);
    if (!pixa)
        return ERROR_INT("pixa not defined", procName, 1);

    n = pixaGetCount(pixa);
    for (i = 0; i < n; i++) {
        modestr = (i == 0) ? "w" : "a";
        pix1 = pixaGetPix(pixa, i, L_CLONE);
        if (pixGetDepth(pix1) == 1)
            pixWriteTiff(fname, pix1, IFF_TIFF_G4, modestr);
        else
            pixWriteTiff(fname, pix1, IFF_TIFF_ZIP, modestr);
        pixDestroy(&pix1);
    }

    return 0;
}


/*!
 * \brief   writeMultipageTiff()
 *
 * \param[in]    dirin   input directory
 * \param[in]    substr  [optional] substring filter on filenames; can be NULL
 * \param[in]    fileout output multipage tiff file
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This writes a set of image files in a directory out
 *          as a multipage tiff file.  The images can be in any
 *          initial file format.
 *      (2) Images with a colormap have the colormap removed before
 *          re-encoding as tiff.
 *      (3) All images are encoded losslessly.  Those with 1 bpp are
 *          encoded 'g4'.  The rest are encoded as 'zip' (flate encoding).
 *          Because it is lossless, this is an expensive method for
 *          saving most rgb images.
 *      (4) The tiff directory overhead is quadratic in the number of
 *          images.  To avoid this for very large numbers of images to be
 *          written, apply the method used in pixaWriteMultipageTiff().
 * </pre>
 */
l_ok
writeMultipageTiff(const char  *dirin,
                   const char  *substr,
                   const char  *fileout)
{
SARRAY  *sa;

    PROCNAME("writeMultipageTiff");

    if (!dirin)
        return ERROR_INT("dirin not defined", procName, 1);
    if (!fileout)
        return ERROR_INT("fileout not defined", procName, 1);

        /* Get all filtered and sorted full pathnames. */
    sa = getSortedPathnamesInDirectory(dirin, substr, 0, 0);

        /* Generate the tiff file */
    writeMultipageTiffSA(sa, fileout);
    sarrayDestroy(&sa);
    return 0;
}


/*!
 * \brief   writeMultipageTiffSA()
 *
 * \param[in]    sa       string array of full path names
 * \param[in]    fileout  output ps file
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) See writeMultipageTiff()
 * </pre>
 */
l_ok
writeMultipageTiffSA(SARRAY      *sa,
                     const char  *fileout)
{
char        *fname;
const char  *op;
l_int32      i, nfiles, firstfile, format;
PIX         *pix;

    PROCNAME("writeMultipageTiffSA");

    if (!sa)
        return ERROR_INT("sa not defined", procName, 1);
    if (!fileout)
        return ERROR_INT("fileout not defined", procName, 1);

    nfiles = sarrayGetCount(sa);
    firstfile = TRUE;
    for (i = 0; i < nfiles; i++) {
        op = (firstfile) ? "w" : "a";
        fname = sarrayGetString(sa, i, L_NOCOPY);
        findFileFormat(fname, &format);
        if (format == IFF_UNKNOWN) {
            L_INFO("format of %s not known\n", procName, fname);
            continue;
        }

        if ((pix = pixRead(fname)) == NULL) {
            L_WARNING("pix not made for file: %s\n", procName, fname);
            continue;
        }
        if (pixGetDepth(pix) == 1)
            pixWriteTiff(fileout, pix, IFF_TIFF_G4, op);
        else
            pixWriteTiff(fileout, pix, IFF_TIFF_ZIP, op);
        firstfile = FALSE;
        pixDestroy(&pix);
    }

    return 0;
}


/*--------------------------------------------------------------*
 *                    Print info to stream                      *
 *--------------------------------------------------------------*/
/*!
 * \brief   fprintTiffInfo()
 *
 * \param[in]    fpout    stream for output of tag data
 * \param[in]    tiffile  input
 * \return  0 if OK; 1 on error
 */
l_ok
fprintTiffInfo(FILE        *fpout,
               const char  *tiffile)
{
TIFF  *tif;

    PROCNAME("fprintTiffInfo");

    if (!tiffile)
        return ERROR_INT("tiffile not defined", procName, 1);
    if (!fpout)
        return ERROR_INT("stream out not defined", procName, 1);

    if ((tif = openTiff(tiffile, "rb")) == NULL)
        return ERROR_INT("tif not open for read", procName, 1);

    TIFFPrintDirectory(tif, fpout, 0);
    TIFFClose(tif);

    return 0;
}


/*--------------------------------------------------------------*
 *                        Get page count                        *
 *--------------------------------------------------------------*/
/*!
 * \brief   tiffGetCount()
 *
 * \param[in]    fp   file stream opened for read
 * \param[out]   pn   number of images
 * \return  0 if OK; 1 on error
 */
l_ok
tiffGetCount(FILE     *fp,
             l_int32  *pn)
{
l_int32  i;
TIFF    *tif;

    PROCNAME("tiffGetCount");

    if (!fp)
        return ERROR_INT("stream not defined", procName, 1);
    if (!pn)
        return ERROR_INT("&n not defined", procName, 1);
    *pn = 0;

    if ((tif = fopenTiff(fp, "r")) == NULL)
        return ERROR_INT("tif not open for read", procName, 1);

    for (i = 1; ; i++) {
        if (TIFFReadDirectory(tif) == 0)
            break;
        if (i == ManyPagesInTiffFile + 1) {
            L_WARNING("big file: more than %d pages\n", procName,
                      ManyPagesInTiffFile);
        }
    }
    *pn = i;
    TIFFCleanup(tif);
    return 0;
}


/*--------------------------------------------------------------*
 *                   Get resolution from tif                    *
 *--------------------------------------------------------------*/
/*!
 * \brief   getTiffResolution()
 *
 * \param[in]    fp            file stream opened for read
 * \param[out]   pxres, pyres  resolution in ppi
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) If neither resolution field is set, this is not an error;
 *          the returned resolution values are 0 (designating 'unknown').
 * </pre>
 */
l_ok
getTiffResolution(FILE     *fp,
                  l_int32  *pxres,
                  l_int32  *pyres)
{
TIFF  *tif;

    PROCNAME("getTiffResolution");

    if (!pxres || !pyres)
        return ERROR_INT("&xres and &yres not both defined", procName, 1);
    *pxres = *pyres = 0;
    if (!fp)
        return ERROR_INT("stream not opened", procName, 1);

    if ((tif = fopenTiff(fp, "r")) == NULL)
        return ERROR_INT("tif not open for read", procName, 1);
    getTiffStreamResolution(tif, pxres, pyres);
    TIFFCleanup(tif);
    return 0;
}


/*!
 * \brief   getTiffStreamResolution()
 *
 * \param[in]    tif            TIFF handle opened for read
 * \param[out]   pxres, pyres   resolution in ppi
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) If neither resolution field is set, this is not an error;
 *          the returned resolution values are 0 (designating 'unknown').
 * </pre>
 */
static l_int32
getTiffStreamResolution(TIFF     *tif,
                        l_int32  *pxres,
                        l_int32  *pyres)
{
l_uint16   resunit;
l_int32    foundxres, foundyres;
l_float32  fxres, fyres;

    PROCNAME("getTiffStreamResolution");

    if (!tif)
        return ERROR_INT("tif not opened", procName, 1);
    if (!pxres || !pyres)
        return ERROR_INT("&xres and &yres not both defined", procName, 1);
    *pxres = *pyres = 0;

    TIFFGetFieldDefaulted(tif, TIFFTAG_RESOLUTIONUNIT, &resunit);
    foundxres = TIFFGetField(tif, TIFFTAG_XRESOLUTION, &fxres);
    foundyres = TIFFGetField(tif, TIFFTAG_YRESOLUTION, &fyres);
    if (!foundxres && !foundyres) return 1;
    if (isnan(fxres) || isnan(fyres)) return 1;
    if (!foundxres && foundyres)
        fxres = fyres;
    else if (foundxres && !foundyres)
        fyres = fxres;

        /* Avoid overflow into int32; set max fxres and fyres to 5 x 10^8 */
    if (fxres < 0 || fxres > (1L << 29) || fyres < 0 || fyres > (1L << 29))
        return ERROR_INT("fxres and/or fyres values are invalid", procName, 1);

    if (resunit == RESUNIT_CENTIMETER) {  /* convert to ppi */
        *pxres = (l_int32)(2.54 * fxres + 0.5);
        *pyres = (l_int32)(2.54 * fyres + 0.5);
    } else {
        *pxres = (l_int32)fxres;
        *pyres = (l_int32)fyres;
    }

    return 0;
}


/*--------------------------------------------------------------*
 *              Get some tiff header information                *
 *--------------------------------------------------------------*/
/*!
 * \brief   readHeaderTiff()
 *
 * \param[in]    filename
 * \param[in]    n          page image number: 0-based
 * \param[out]   pw         [optional] width
 * \param[out]   ph         [optional] height
 * \param[out]   pbps       [optional] bits per sample -- 1, 2, 4 or 8
 * \param[out]   pspp       [optional] samples per pixel -- 1 or 3
 * \param[out]   pres       [optional] resolution in x dir; NULL to ignore
 * \param[out]   pcmap      [optional] colormap exists; input NULL to ignore
 * \param[out]   pformat    [optional] tiff format; input NULL to ignore
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) If there is a colormap, cmap is returned as 1; else 0.
 *      (2) If %n is equal to or greater than the number of images, returns 1.
 * </pre>
 */
l_ok
readHeaderTiff(const char *filename,
               l_int32     n,
               l_int32    *pw,
               l_int32    *ph,
               l_int32    *pbps,
               l_int32    *pspp,
               l_int32    *pres,
               l_int32    *pcmap,
               l_int32    *pformat)
{
l_int32  ret;
FILE    *fp;

    PROCNAME("readHeaderTiff");

    if (pw) *pw = 0;
    if (ph) *ph = 0;
    if (pbps) *pbps = 0;
    if (pspp) *pspp = 0;
    if (pres) *pres = 0;
    if (pcmap) *pcmap = 0;
    if (pformat) *pformat = 0;
    if (!filename)
        return ERROR_INT("filename not defined", procName, 1);
    if (!pw && !ph && !pbps && !pspp && !pres && !pcmap && !pformat)
        return ERROR_INT("no results requested", procName, 1);

    if ((fp = fopenReadStream(filename)) == NULL)
        return ERROR_INT("image file not found", procName, 1);
    ret = freadHeaderTiff(fp, n, pw, ph, pbps, pspp, pres, pcmap, pformat);
    fclose(fp);
    return ret;
}


/*!
 * \brief   freadHeaderTiff()
 *
 * \param[in]    fp       file stream
 * \param[in]    n        page image number: 0-based
 * \param[out]   pw       [optional] width
 * \param[out]   ph       [optional] height
 * \param[out]   pbps     [optional] bits per sample -- 1, 2, 4 or 8
 * \param[out]   pspp     [optional] samples per pixel -- 1 or 3
 * \param[out]   pres     [optional] resolution in x dir; NULL to ignore
 * \param[out]   pcmap    [optional] colormap exists; input NULL to ignore
 * \param[out]   pformat  [optional] tiff format; input NULL to ignore
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) If there is a colormap, cmap is returned as 1; else 0.
 *      (2) If %n is equal to or greater than the number of images, returns 1.
 * </pre>
 */
l_ok
freadHeaderTiff(FILE     *fp,
                l_int32   n,
                l_int32  *pw,
                l_int32  *ph,
                l_int32  *pbps,
                l_int32  *pspp,
                l_int32  *pres,
                l_int32  *pcmap,
                l_int32  *pformat)
{
l_int32  i, ret, format;
TIFF    *tif;

    PROCNAME("freadHeaderTiff");

    if (pw) *pw = 0;
    if (ph) *ph = 0;
    if (pbps) *pbps = 0;
    if (pspp) *pspp = 0;
    if (pres) *pres = 0;
    if (pcmap) *pcmap = 0;
    if (pformat) *pformat = 0;
    if (!fp)
        return ERROR_INT("stream not defined", procName, 1);
    if (n < 0)
        return ERROR_INT("image index must be >= 0", procName, 1);
    if (!pw && !ph && !pbps && !pspp && !pres && !pcmap && !pformat)
        return ERROR_INT("no results requested", procName, 1);

    findFileFormatStream(fp, &format);
    if (!L_FORMAT_IS_TIFF(format))
        return ERROR_INT("file not tiff format", procName, 1);

    if ((tif = fopenTiff(fp, "r")) == NULL)
        return ERROR_INT("tif not open for read", procName, 1);

    for (i = 0; i < n; i++) {
        if (TIFFReadDirectory(tif) == 0)
            return ERROR_INT("image n not found in file", procName, 1);
    }

    ret = tiffReadHeaderTiff(tif, pw, ph, pbps, pspp, pres, pcmap, pformat);
    TIFFCleanup(tif);
    return ret;
}


/*!
 * \brief   readHeaderMemTiff()
 *
 * \param[in]    cdata     const; tiff-encoded
 * \param[in]    size      size of data
 * \param[in]    n         page image number: 0-based
 * \param[out]   pw        [optional] width
 * \param[out]   ph        [optional] height
 * \param[out]   pbps      [optional] bits per sample -- 1, 2, 4 or 8
 * \param[out]   pspp      [optional] samples per pixel -- 1 or 3
 * \param[out]   pres      [optional] resolution in x dir; NULL to ignore
 * \param[out]   pcmap     [optional] colormap exists; input NULL to ignore
 * \param[out]   pformat   [optional] tiff format; input NULL to ignore
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Use TIFFClose(); TIFFCleanup() doesn't free internal memstream.
 * </pre>
 */
l_ok
readHeaderMemTiff(const l_uint8  *cdata,
                  size_t          size,
                  l_int32         n,
                  l_int32        *pw,
                  l_int32        *ph,
                  l_int32        *pbps,
                  l_int32        *pspp,
                  l_int32        *pres,
                  l_int32        *pcmap,
                  l_int32        *pformat)
{
l_uint8  *data;
l_int32   i, ret;
TIFF     *tif;

    PROCNAME("readHeaderMemTiff");

    if (pw) *pw = 0;
    if (ph) *ph = 0;
    if (pbps) *pbps = 0;
    if (pspp) *pspp = 0;
    if (pres) *pres = 0;
    if (pcmap) *pcmap = 0;
    if (pformat) *pformat = 0;
    if (!pw && !ph && !pbps && !pspp && !pres && !pcmap && !pformat)
        return ERROR_INT("no results requested", procName, 1);
    if (!cdata)
        return ERROR_INT("cdata not defined", procName, 1);

        /* Open a tiff stream to memory */
    data = (l_uint8 *)cdata;  /* we're really not going to change this */
    if ((tif = fopenTiffMemstream("tifferror", "r", &data, &size)) == NULL)
        return ERROR_INT("tiff stream not opened", procName, 1);

    for (i = 0; i < n; i++) {
        if (TIFFReadDirectory(tif) == 0) {
            TIFFClose(tif);
            return ERROR_INT("image n not found in file", procName, 1);
        }
    }

    ret = tiffReadHeaderTiff(tif, pw, ph, pbps, pspp, pres, pcmap, pformat);
    TIFFClose(tif);
    return ret;
}


/*!
 * \brief   tiffReadHeaderTiff()
 *
 * \param[in]    tif
 * \param[out]   pw        [optional] width
 * \param[out]   ph        [optional] height
 * \param[out]   pbps      [optional] bits per sample -- 1, 2, 4 or 8
 * \param[out]   pspp      [optional] samples per pixel -- 1 or 3
 * \param[out]   pres      [optional] resolution in x dir; NULL to ignore
 * \param[out]   pcmap     [optional] cmap exists; input NULL to ignore
 * \param[out]   pformat   [optional] tiff format; input NULL to ignore
 * \return  0 if OK, 1 on error
 */
static l_int32
tiffReadHeaderTiff(TIFF     *tif,
                   l_int32  *pw,
                   l_int32  *ph,
                   l_int32  *pbps,
                   l_int32  *pspp,
                   l_int32  *pres,
                   l_int32  *pcmap,
                   l_int32  *pformat)
{
l_uint16   tiffcomp;
l_uint16   bps, spp;
l_uint16  *rmap, *gmap, *bmap;
l_int32    xres, yres;
l_uint32   w, h;

    PROCNAME("tiffReadHeaderTiff");

    if (!tif)
        return ERROR_INT("tif not opened", procName, 1);

    TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
    TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
    TIFFGetFieldDefaulted(tif, TIFFTAG_BITSPERSAMPLE, &bps);
    TIFFGetFieldDefaulted(tif, TIFFTAG_SAMPLESPERPIXEL, &spp);
    if (w < 1 || h < 1)
        return ERROR_INT("tif w and h not both > 0", procName, 1);
    if (bps != 1 && bps != 2 && bps != 4 && bps != 8 && bps != 16)
        return ERROR_INT("bps not in set {1,2,4,8,16}", procName, 1);
    if (spp != 1 && spp != 2 && spp != 3 && spp != 4)
        return ERROR_INT("spp not in set {1,2,3,4}", procName, 1);
    if (pw) *pw = w;
    if (ph) *ph = h;
    if (pbps) *pbps = bps;
    if (pspp) *pspp = spp;
    if (pres) {
        *pres = 300;  /* default ppi */
        if (getTiffStreamResolution(tif, &xres, &yres) == 0)
            *pres = (l_int32)xres;
    }
    if (pcmap) {
        *pcmap = 0;
        if (TIFFGetField(tif, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap))
            *pcmap = 1;
    }
    if (pformat) {
        TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &tiffcomp);
        *pformat = getTiffCompressedFormat(tiffcomp);
    }
    return 0;
}


/*!
 * \brief   findTiffCompression()
 *
 * \param[in]    fp         file stream; must be rewound to BOF
 * \param[out]   pcomptype  compression type
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) The returned compression type is that defined in
 *          the enum in imageio.h.  It is not the tiff flag value.
 *      (2) The compression type is initialized to IFF_UNKNOWN.
 *          If it is not one of the specified types, the returned
 *          type is IFF_TIFF, which indicates no compression.
 *      (3) When this function is called, the stream must be at BOF.
 *          If the opened stream is to be used again to read the
 *          file, it must be rewound to BOF after calling this function.
 * </pre>
 */
l_ok
findTiffCompression(FILE     *fp,
                    l_int32  *pcomptype)
{
l_uint16  tiffcomp;
TIFF     *tif;

    PROCNAME("findTiffCompression");

    if (!pcomptype)
        return ERROR_INT("&comptype not defined", procName, 1);
    *pcomptype = IFF_UNKNOWN;  /* init */
    if (!fp)
        return ERROR_INT("stream not defined", procName, 1);

    if ((tif = fopenTiff(fp, "r")) == NULL)
        return ERROR_INT("tif not opened", procName, 1);
    TIFFGetFieldDefaulted(tif, TIFFTAG_COMPRESSION, &tiffcomp);
    *pcomptype = getTiffCompressedFormat(tiffcomp);
    TIFFCleanup(tif);
    return 0;
}


/*!
 * \brief   getTiffCompressedFormat()
 *
 * \param[in]    tiffcomp    defined in tiff.h
 * \return  compression format defined in imageio.h
 *
 * <pre>
 * Notes:
 *      (1) The input must be the actual tiff compression type
 *          returned by a tiff library call.  It should always be
 *          a valid tiff type.
 *      (2) The return type is defined in the enum in imageio.h.
 * </pre>
 */
static l_int32
getTiffCompressedFormat(l_uint16  tiffcomp)
{
l_int32  comptype;

    switch (tiffcomp)
    {
    case COMPRESSION_CCITTFAX4:
        comptype = IFF_TIFF_G4;
        break;
    case COMPRESSION_CCITTFAX3:
        comptype = IFF_TIFF_G3;
        break;
    case COMPRESSION_CCITTRLE:
        comptype = IFF_TIFF_RLE;
        break;
    case COMPRESSION_PACKBITS:
        comptype = IFF_TIFF_PACKBITS;
        break;
    case COMPRESSION_LZW:
        comptype = IFF_TIFF_LZW;
        break;
    case COMPRESSION_ADOBE_DEFLATE:
        comptype = IFF_TIFF_ZIP;
        break;
    case COMPRESSION_JPEG:
        comptype = IFF_TIFF_JPEG;
        break;
    default:
        comptype = IFF_TIFF;
        break;
    }
    return comptype;
}


/*--------------------------------------------------------------*
 *                   Extraction of tiff g4 data                 *
 *--------------------------------------------------------------*/
/*!
 * \brief   extractG4DataFromFile()
 *
 * \param[in]    filein
 * \param[out]   pdata         binary data of ccitt g4 encoded stream
 * \param[out]   pnbytes       size of binary data
 * \param[out]   pw            [optional] image width
 * \param[out]   ph            [optional] image height
 * \param[out]   pminisblack   [optional] boolean
 * \return  0 if OK, 1 on error
 */
l_ok
extractG4DataFromFile(const char  *filein,
                      l_uint8    **pdata,
                      size_t      *pnbytes,
                      l_int32     *pw,
                      l_int32     *ph,
                      l_int32     *pminisblack)
{
l_uint8  *inarray, *data;
l_uint16  minisblack, comptype;  /* accessors require l_uint16 */
l_int32   istiff;
l_uint32  w, h, rowsperstrip;  /* accessors require l_uint32 */
l_uint32  diroff;
size_t    fbytes, nbytes;
FILE     *fpin;
TIFF     *tif;

    PROCNAME("extractG4DataFromFile");

    if (!pdata)
        return ERROR_INT("&data not defined", procName, 1);
    if (!pnbytes)
        return ERROR_INT("&nbytes not defined", procName, 1);
    if (!pw && !ph && !pminisblack)
        return ERROR_INT("no output data requested", procName, 1);
    *pdata = NULL;
    *pnbytes = 0;

    if ((fpin = fopenReadStream(filein)) == NULL)
        return ERROR_INT("stream not opened to file", procName, 1);
    istiff = fileFormatIsTiff(fpin);
    fclose(fpin);
    if (!istiff)
        return ERROR_INT("filein not tiff", procName, 1);

    if ((inarray = l_binaryRead(filein, &fbytes)) == NULL)
        return ERROR_INT("inarray not made", procName, 1);

        /* Get metadata about the image */
    if ((tif = openTiff(filein, "rb")) == NULL) {
        LEPT_FREE(inarray);
        return ERROR_INT("tif not open for read", procName, 1);
    }
    TIFFGetField(tif, TIFFTAG_COMPRESSION, &comptype);
    if (comptype != COMPRESSION_CCITTFAX4) {
        LEPT_FREE(inarray);
        TIFFClose(tif);
        return ERROR_INT("filein is not g4 compressed", procName, 1);
    }

    TIFFGetField(tif, TIFFTAG_IMAGEWIDTH, &w);
    TIFFGetField(tif, TIFFTAG_IMAGELENGTH, &h);
    TIFFGetField(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
    if (h != rowsperstrip)
        L_WARNING("more than 1 strip\n", procName);
    TIFFGetField(tif, TIFFTAG_PHOTOMETRIC, &minisblack);  /* for 1 bpp */
/*    TIFFPrintDirectory(tif, stderr, 0); */
    TIFFClose(tif);
    if (pw) *pw = (l_int32)w;
    if (ph) *ph = (l_int32)h;
    if (pminisblack) *pminisblack = (l_int32)minisblack;

        /* The header has 8 bytes: the first 2 are the magic number,
         * the next 2 are the version, and the last 4 are the
         * offset to the first directory.  That's what we want here.
         * We have to test the byte order before decoding 4 bytes! */
    if (inarray[0] == 0x4d) {  /* big-endian */
        diroff = (inarray[4] << 24) | (inarray[5] << 16) |
                 (inarray[6] << 8) | inarray[7];
    } else  {   /* inarray[0] == 0x49 :  little-endian */
        diroff = (inarray[7] << 24) | (inarray[6] << 16) |
                 (inarray[5] << 8) | inarray[4];
    }
/*    lept_stderr(" diroff = %d, %x\n", diroff, diroff); */

        /* Extract the ccittg4 encoded data from the tiff file.
         * We skip the 8 byte header and take nbytes of data,
         * up to the beginning of the directory (at diroff)  */
    nbytes = diroff - 8;
    if (nbytes > MaxNumTiffBytes) {
        LEPT_FREE(inarray);
        L_ERROR("requesting %zu bytes > %zu\n", procName,
                nbytes, MaxNumTiffBytes);
        return 1;
    }
    *pnbytes = nbytes;
    if ((data = (l_uint8 *)LEPT_CALLOC(nbytes, sizeof(l_uint8))) == NULL) {
        LEPT_FREE(inarray);
        return ERROR_INT("data not allocated", procName, 1);
    }
    *pdata = data;
    memcpy(data, inarray + 8, nbytes);
    LEPT_FREE(inarray);

    return 0;
}


/*--------------------------------------------------------------*
 *               Open tiff stream from file stream              *
 *--------------------------------------------------------------*/
/*!
 * \brief   fopenTiff()
 *
 * \param[in]    fp           file stream
 * \param[in]    modestring   "r", "w", ...
 * \return  tiff data structure, opened for a file descriptor
 *
 * <pre>
 * Notes:
 *      (1) Why is this here?  Leffler did not provide a function that
 *          takes a stream and gives a TIFF.  He only gave one that
 *          generates a TIFF starting with a file descriptor.  So we
 *          need to make it here, because it is useful to have functions
 *          that take a stream as input.
 *      (2) We use TIFFClientOpen() together with a set of static wrapper
 *          functions which map TIFF read, write, seek, close and size.
 *          to functions expecting a cookie of type stream (i.e. FILE *).
 *          This implementation was contributed by Jürgen Buchmüller.
 * </pre>
 */
static TIFF *
fopenTiff(FILE        *fp,
          const char  *modestring)
{
    PROCNAME("fopenTiff");

    if (!fp)
        return (TIFF *)ERROR_PTR("stream not opened", procName, NULL);
    if (!modestring)
        return (TIFF *)ERROR_PTR("modestring not defined", procName, NULL);

    TIFFSetWarningHandler(NULL);  /* disable warnings */
    TIFFSetErrorHandler(NULL);  /* disable error messages */

    fseek(fp, 0, SEEK_SET);
    return TIFFClientOpen("TIFFstream", modestring, (thandle_t)fp,
                          lept_read_proc, lept_write_proc, lept_seek_proc,
                          lept_close_proc, lept_size_proc, NULL, NULL);
}


/*--------------------------------------------------------------*
 *                      Wrapper for TIFFOpen                    *
 *--------------------------------------------------------------*/
/*!
 * \brief   openTiff()
 *
 * \param[in]    filename
 * \param[in]    modestring   "r", "w", ...
 * \return  tiff data structure
 *
 * <pre>
 * Notes:
 *      (1) This handles multi-platform file naming.
 * </pre>
 */
static TIFF *
openTiff(const char  *filename,
         const char  *modestring)
{
char  *fname;
TIFF  *tif;

    PROCNAME("openTiff");

    if (!filename)
        return (TIFF *)ERROR_PTR("filename not defined", procName, NULL);
    if (!modestring)
        return (TIFF *)ERROR_PTR("modestring not defined", procName, NULL);

    TIFFSetWarningHandler(NULL);  /* disable warnings */
    TIFFSetErrorHandler(NULL);  /* disable error messages */

    fname = genPathname(filename, NULL);
    tif = TIFFOpen(fname, modestring);
    LEPT_FREE(fname);
    return tif;
}


/*----------------------------------------------------------------------*
 *     Memory I/O: reading memory --> pix and writing pix --> memory    *
 *----------------------------------------------------------------------*/
/*  It would be nice to use open_memstream() and fmemopen()
 *  for writing and reading to memory, rsp.  These functions manage
 *  memory for writes and reads that use a file streams interface.
 *  Unfortunately, the tiff library only has an interface for reading
 *  and writing to file descriptors, not to file streams.  The tiff
 *  library procedure is to open a "tiff stream" and read/write to it.
 *  The library provides a client interface for managing the I/O
 *  from memory, which requires seven callbacks.  See the TIFFClientOpen
 *  man page for callback signatures.  Adam Langley provided the code
 *  to do this.  */

/*!
 * \brief   Memory stream buffer used with TIFFClientOpen()
 *
 *  The L_Memstram %buffer has different functions in writing and reading.
 *
 *     * In reading, it is assigned to the data and read from as
 *       the tiff library uncompresses the data and generates the pix.
 *       The %offset points to the current read position in the data,
 *       and the %hw always gives the number of bytes of data.
 *       The %outdata and %outsize ptrs are not used.
 *       When finished, tiffCloseCallback() simply frees the L_Memstream.
 *
 *     * In writing, it accepts the data that the tiff library
 *       produces when a pix is compressed.  the buffer points to a
 *       malloced area of %bufsize bytes.  The current writing position
 *       in the buffer is %offset and the most ever written is %hw.
 *       The buffer is expanded as necessary.  When finished,
 *       tiffCloseCallback() assigns the %outdata and %outsize ptrs
 *       to the %buffer and %bufsize results, and frees the L_Memstream.
 */
struct L_Memstream
{
    l_uint8   *buffer;    /* expands to hold data when written to;         */
                          /* fixed size when read from.                    */
    size_t     bufsize;   /* current size allocated when written to;       */
                          /* fixed size of input data when read from.      */
    size_t     offset;    /* byte offset from beginning of buffer.         */
    size_t     hw;        /* high-water mark; max bytes in buffer.         */
    l_uint8  **poutdata;  /* input param for writing; data goes here.      */
    size_t    *poutsize;  /* input param for writing; data size goes here. */
};
typedef struct L_Memstream  L_MEMSTREAM;


    /* These are static functions for memory I/O */
static L_MEMSTREAM *memstreamCreateForRead(l_uint8 *indata, size_t pinsize);
static L_MEMSTREAM *memstreamCreateForWrite(l_uint8 **poutdata,
                                            size_t *poutsize);
static tsize_t tiffReadCallback(thandle_t handle, tdata_t data, tsize_t length);
static tsize_t tiffWriteCallback(thandle_t handle, tdata_t data,
                                 tsize_t length);
static toff_t tiffSeekCallback(thandle_t handle, toff_t offset, l_int32 whence);
static l_int32 tiffCloseCallback(thandle_t handle);
static toff_t tiffSizeCallback(thandle_t handle);
static l_int32 tiffMapCallback(thandle_t handle, tdata_t *data, toff_t *length);
static void tiffUnmapCallback(thandle_t handle, tdata_t data, toff_t length);


static L_MEMSTREAM *
memstreamCreateForRead(l_uint8  *indata,
                       size_t    insize)
{
L_MEMSTREAM  *mstream;

    mstream = (L_MEMSTREAM *)LEPT_CALLOC(1, sizeof(L_MEMSTREAM));
    mstream->buffer = indata;   /* handle to input data array */
    mstream->bufsize = insize;  /* amount of input data */
    mstream->hw = insize;       /* high-water mark fixed at input data size */
    mstream->offset = 0;        /* offset always starts at 0 */
    return mstream;
}


static L_MEMSTREAM *
memstreamCreateForWrite(l_uint8  **poutdata,
                        size_t    *poutsize)
{
L_MEMSTREAM  *mstream;

    mstream = (L_MEMSTREAM *)LEPT_CALLOC(1, sizeof(L_MEMSTREAM));
    mstream->buffer = (l_uint8 *)LEPT_CALLOC(8 * 1024, 1);
    mstream->bufsize = 8 * 1024;
    mstream->poutdata = poutdata;  /* used only at end of write */
    mstream->poutsize = poutsize;  /* ditto  */
    mstream->hw = mstream->offset = 0;
    return mstream;
}


static tsize_t
tiffReadCallback(thandle_t  handle,
                 tdata_t    data,
                 tsize_t    length)
{
L_MEMSTREAM  *mstream;
size_t        amount;

    mstream = (L_MEMSTREAM *)handle;
    amount = L_MIN((size_t)length, mstream->hw - mstream->offset);

        /* Fuzzed files can create this condition! */
    if (mstream->offset + amount < amount ||  /* overflow */
        mstream->offset + amount > mstream->hw) {
        lept_stderr("Bad file: amount too big: %zu\n", amount);
        return 0;
    }

    memcpy(data, mstream->buffer + mstream->offset, amount);
    mstream->offset += amount;
    return amount;
}


static tsize_t
tiffWriteCallback(thandle_t  handle,
                  tdata_t    data,
                  tsize_t    length)
{
L_MEMSTREAM  *mstream;
size_t        newsize;

        /* reallocNew() uses calloc to initialize the array.
         * If malloc is used instead, for some of the encoding methods,
         * not all the data in 'bufsize' bytes in the buffer will
         * have been initialized by the end of the compression. */
    mstream = (L_MEMSTREAM *)handle;
    if (mstream->offset + length > mstream->bufsize) {
        newsize = 2 * (mstream->offset + length);
        mstream->buffer = (l_uint8 *)reallocNew((void **)&mstream->buffer,
                                                mstream->hw, newsize);
        mstream->bufsize = newsize;
    }

    memcpy(mstream->buffer + mstream->offset, data, length);
    mstream->offset += length;
    mstream->hw = L_MAX(mstream->offset, mstream->hw);
    return length;
}


static toff_t
tiffSeekCallback(thandle_t  handle,
                 toff_t     offset,
                 l_int32    whence)
{
L_MEMSTREAM  *mstream;

    PROCNAME("tiffSeekCallback");
    mstream = (L_MEMSTREAM *)handle;
    switch (whence) {
        case SEEK_SET:
/*            lept_stderr("seek_set: offset = %d\n", offset); */
            if((size_t)offset != offset) {  /* size_t overflow on uint32 */
                return (toff_t)ERROR_INT("too large offset value", procName, 1);
            }
            mstream->offset = offset;
            break;
        case SEEK_CUR:
/*            lept_stderr("seek_cur: offset = %d\n", offset); */
            mstream->offset += offset;
            break;
        case SEEK_END:
/*            lept_stderr("seek end: hw = %d, offset = %d\n",
                    mstream->hw, offset); */
            mstream->offset = mstream->hw - offset;  /* offset >= 0 */
            break;
        default:
            return (toff_t)ERROR_INT("bad whence value", procName,
                                     mstream->offset);
    }

    return mstream->offset;
}


static l_int32
tiffCloseCallback(thandle_t  handle)
{
L_MEMSTREAM  *mstream;

    mstream = (L_MEMSTREAM *)handle;
    if (mstream->poutdata) {   /* writing: save the output data */
        *mstream->poutdata = mstream->buffer;
        *mstream->poutsize = mstream->hw;
    }
    LEPT_FREE(mstream);  /* never free the buffer! */
    return 0;
}


static toff_t
tiffSizeCallback(thandle_t  handle)
{
L_MEMSTREAM  *mstream;

    mstream = (L_MEMSTREAM *)handle;
    return mstream->hw;
}


static l_int32
tiffMapCallback(thandle_t  handle,
                tdata_t   *data,
                toff_t    *length)
{
L_MEMSTREAM  *mstream;

    mstream = (L_MEMSTREAM *)handle;
    *data = mstream->buffer;
    *length = mstream->hw;
    return 0;
}


static void
tiffUnmapCallback(thandle_t  handle,
                  tdata_t    data,
                  toff_t     length)
{
    return;
}


/*!
 * \brief   fopenTiffMemstream()
 *
 * \param[in]    filename    for error output; can be ""
 * \param[in]    operation   "w" for write, "r" for read
 * \param[out]   pdata       written data
 * \param[out]   pdatasize   size of written data
 * \return  tiff data structure, opened for write to memory
 *
 * <pre>
 * Notes:
 *      (1) This wraps up a number of callbacks for either:
 *            * reading from tiff in memory buffer --> pix
 *            * writing from pix --> tiff in memory buffer
 *      (2) After use, the memstream is automatically destroyed when
 *          TIFFClose() is called.  TIFFCleanup() doesn't free the memstream.
 *      (3) This does not work in append mode, and in write mode it
 *          does not append.
 * </pre>
 */
static TIFF *
fopenTiffMemstream(const char  *filename,
                   const char  *operation,
                   l_uint8    **pdata,
                   size_t      *pdatasize)
{
L_MEMSTREAM  *mstream;
TIFF         *tif;

    PROCNAME("fopenTiffMemstream");

    if (!filename)
        return (TIFF *)ERROR_PTR("filename not defined", procName, NULL);
    if (!operation)
        return (TIFF *)ERROR_PTR("operation not defined", procName, NULL);
    if (!pdata)
        return (TIFF *)ERROR_PTR("&data not defined", procName, NULL);
    if (!pdatasize)
        return (TIFF *)ERROR_PTR("&datasize not defined", procName, NULL);
    if (strcmp(operation, "r") && strcmp(operation, "w"))
        return (TIFF *)ERROR_PTR("op not 'r' or 'w'", procName, NULL);

    if (!strcmp(operation, "r"))
        mstream = memstreamCreateForRead(*pdata, *pdatasize);
    else
        mstream = memstreamCreateForWrite(pdata, pdatasize);

    TIFFSetWarningHandler(NULL);  /* disable warnings */
    TIFFSetErrorHandler(NULL);  /* disable error messages */

    tif = TIFFClientOpen(filename, operation, (thandle_t)mstream,
                         tiffReadCallback, tiffWriteCallback,
                         tiffSeekCallback, tiffCloseCallback,
                         tiffSizeCallback, tiffMapCallback,
                         tiffUnmapCallback);
    if (!tif)
        LEPT_FREE(mstream);
    return tif;
}


/*!
 * \brief   pixReadMemTiff()
 *
 * \param[in]    cdata    const; tiff-encoded
 * \param[in]    size     size of cdata
 * \param[in]    n        page image number: 0-based
 * \return  pix, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) This is a version of pixReadTiff(), where the data is read
 *          from a memory buffer and uncompressed.
 *      (2) Use TIFFClose(); TIFFCleanup() doesn't free internal memstream.
 *      (3) No warning messages on failure, because of how multi-page
 *          TIFF reading works. You are supposed to keep trying until
 *          it stops working.
 *      (4) Tiff directory overhead is linear in the input page number.
 *          If reading many images, use pixReadMemFromMultipageTiff().
 * </pre>
 */
PIX *
pixReadMemTiff(const l_uint8  *cdata,
               size_t          size,
               l_int32         n)
{
l_uint8  *data;
l_int32   i;
PIX      *pix;
TIFF     *tif;

    PROCNAME("pixReadMemTiff");

    if (!cdata)
        return (PIX *)ERROR_PTR("cdata not defined", procName, NULL);

    data = (l_uint8 *)cdata;  /* we're really not going to change this */
    if ((tif = fopenTiffMemstream("tifferror", "r", &data, &size)) == NULL)
        return (PIX *)ERROR_PTR("tiff stream not opened", procName, NULL);

    pix = NULL;
    for (i = 0; ; i++) {
        if (i == n) {
            if ((pix = pixReadFromTiffStream(tif)) == NULL) {
                TIFFClose(tif);
                return NULL;
            }
            pixSetInputFormat(pix, IFF_TIFF);
            break;
        }
        if (TIFFReadDirectory(tif) == 0)
            break;
        if (i == ManyPagesInTiffFile + 1) {
            L_WARNING("big file: more than %d pages\n", procName,
                      ManyPagesInTiffFile);
        }
    }

    TIFFClose(tif);
    return pix;
}


/*!
 * \brief   pixReadMemFromMultipageTiff()
 *
 * \param[in]    cdata      const; tiff-encoded
 * \param[in]    size       size of cdata
 * \param[in,out]  poffset  set offset to 0 for first image
 * \return  pix, or NULL on error or if previous call returned the last image
 *
 * <pre>
 * Notes:
 *      (1) This is a read-from-memory version of pixReadFromMultipageTiff().
 *          See that function for usage.
 *      (2) If reading sequentially from the tiff data, this is more
 *          efficient than pixReadMemTiff(), which has an overhead
 *          proportional to the image index n.
 *      (3) Example usage for reading all the images:
 *            size_t offset = 0;
 *            do {
 *                Pix *pix = pixReadMemFromMultipageTiff(data, size, &offset);
 *                // do something with pix
 *            } while (offset != 0);
 * </pre>
 */
PIX *
pixReadMemFromMultipageTiff(const l_uint8  *cdata,
                            size_t          size,
                            size_t         *poffset)
{
l_uint8  *data;
l_int32   retval;
size_t    offset;
PIX      *pix;
TIFF     *tif;

    PROCNAME("pixReadMemFromMultipageTiff");

    if (!cdata)
        return (PIX *)ERROR_PTR("cdata not defined", procName, NULL);
    if (!poffset)
        return (PIX *)ERROR_PTR("&offset not defined", procName, NULL);

    data = (l_uint8 *)cdata;  /* we're really not going to change this */
    if ((tif = fopenTiffMemstream("tifferror", "r", &data, &size)) == NULL)
        return (PIX *)ERROR_PTR("tiff stream not opened", procName, NULL);

        /* Set ptrs in the TIFF to the beginning of the image */
    offset = *poffset;
    retval = (offset == 0) ? TIFFSetDirectory(tif, 0)
                           : TIFFSetSubDirectory(tif, offset);
    if (retval == 0) {
        TIFFClose(tif);
        return NULL;
    }

    if ((pix = pixReadFromTiffStream(tif)) == NULL) {
        TIFFClose(tif);
        return NULL;
    }

        /* Advance to the next image and return the new offset */
    TIFFReadDirectory(tif);
    *poffset = TIFFCurrentDirOffset(tif);
    TIFFClose(tif);
    return pix;
}


/*!
 * \brief   pixaReadMemMultipageTiff()
 *
 * \param[in]    data    const; multiple pages; tiff-encoded
 * \param[in]    size    size of cdata
 * \return  pixa, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) This is an O(n) read-from-memory version of pixaReadMultipageTiff().
 * </pre>
 */
PIXA *
pixaReadMemMultipageTiff(const l_uint8  *data,
                         size_t          size)
{
size_t  offset;
PIX    *pix;
PIXA   *pixa;

    PROCNAME("pixaReadMemMultipageTiff");

    if (!data)
        return (PIXA *)ERROR_PTR("data not defined", procName, NULL);

    offset = 0;
    pixa = pixaCreate(0);
    do {
        pix = pixReadMemFromMultipageTiff(data, size, &offset);
        pixaAddPix(pixa, pix, L_INSERT);
    } while (offset != 0);
    return pixa;
}


/*!
 * \brief   pixaWriteMemMultipageTiff()
 *
 * \param[out]    pdata   const; tiff-encoded
 * \param[out]    psize   size of data
 * \param[in]     pixa    any depth; colormap will be removed
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) fopenTiffMemstream() does not work in append mode, so we
 *          must work-around with a temporary file.
 *      (2) Getting a file stream from
 *            open_memstream((char **)pdata, psize)
 *          does not work with the tiff directory.
 * </pre>
 */
l_ok
pixaWriteMemMultipageTiff(l_uint8  **pdata,
                          size_t    *psize,
                          PIXA      *pixa)
{
const char  *modestr;
l_int32      i, n;
FILE        *fp;
PIX         *pix1;

    PROCNAME("pixaWriteMemMultipageTiff");

    if (pdata) *pdata = NULL;
    if (!pdata)
        return ERROR_INT("pdata not defined", procName, 1);
    if (!pixa)
        return ERROR_INT("pixa not defined", procName, 1);

#ifdef _WIN32
    if ((fp = fopenWriteWinTempfile()) == NULL)
        return ERROR_INT("tmpfile stream not opened", procName, 1);
#else
    if ((fp = tmpfile()) == NULL)
        return ERROR_INT("tmpfile stream not opened", procName, 1);
#endif  /* _WIN32 */

    n = pixaGetCount(pixa);
    for (i = 0; i < n; i++) {
        modestr = (i == 0) ? "w" : "a";
        pix1 = pixaGetPix(pixa, i, L_CLONE);
        if (pixGetDepth(pix1) == 1)
            pixWriteStreamTiffWA(fp, pix1, IFF_TIFF_G4, modestr);
        else
            pixWriteStreamTiffWA(fp, pix1, IFF_TIFF_ZIP, modestr);
        pixDestroy(&pix1);
    }

    rewind(fp);
    *pdata = l_binaryReadStream(fp, psize);
    fclose(fp);
    return 0;
}


/*!
 * \brief   pixWriteMemTiff()
 *
 * \param[out]   pdata     data of tiff compressed image
 * \param[out]   psize     size of returned data
 * \param[in]    pix
 * \param[in]    comptype  IFF_TIFF, IFF_TIFF_RLE, IFF_TIFF_PACKBITS,
 *                         IFF_TIFF_G3, IFF_TIFF_G4,
 *                         IFF_TIFF_LZW, IFF_TIFF_ZIP, IFF_TIFF_JPEG
 * \return  0 if OK, 1 on error
 *
 *  Usage:
 *      1) See pixWriteTiff(.  This version writes to
 *          memory instead of to a file.
 */
l_ok
pixWriteMemTiff(l_uint8  **pdata,
                size_t    *psize,
                PIX       *pix,
                l_int32    comptype)
{
    return pixWriteMemTiffCustom(pdata, psize, pix, comptype,
                                 NULL, NULL, NULL, NULL);
}


/*!
 * \brief   pixWriteMemTiffCustom()
 *
 * \param[out]   pdata     data of tiff compressed image
 * \param[out]   psize     size of returned data
 * \param[in]    pix
 * \param[in]    comptype  IFF_TIFF, IFF_TIFF_RLE, IFF_TIFF_PACKBITS,
 *                         IFF_TIFF_G3, IFF_TIFF_G4,
 *                         IFF_TIFF_LZW, IFF_TIFF_ZIP, IFF_TIFF_JPEG
 * \param[in]    natags    [optional] NUMA of custom tiff tags
 * \param[in]    savals    [optional] SARRAY of values
 * \param[in]    satypes   [optional] SARRAY of types
 * \param[in]    nasizes   [optional] NUMA of sizes
 * \return  0 if OK, 1 on error
 *
 *  Usage:
 *      1) See pixWriteTiffCustom(.  This version writes to
 *          memory instead of to a file.
 *      2) Use TIFFClose(); TIFFCleanup( doesn't free internal memstream.
 */
l_ok
pixWriteMemTiffCustom(l_uint8  **pdata,
                      size_t    *psize,
                      PIX       *pix,
                      l_int32    comptype,
                      NUMA      *natags,
                      SARRAY    *savals,
                      SARRAY    *satypes,
                      NUMA      *nasizes)
{
l_int32  ret;
TIFF    *tif;

    PROCNAME("pixWriteMemTiffCustom");

    if (!pdata)
        return ERROR_INT("&data not defined", procName, 1);
    if (!psize)
        return ERROR_INT("&size not defined", procName, 1);
    if (!pix)
        return ERROR_INT("&pix not defined", procName, 1);
    if (pixGetDepth(pix) != 1 && comptype != IFF_TIFF &&
        comptype != IFF_TIFF_LZW && comptype != IFF_TIFF_ZIP &&
        comptype != IFF_TIFF_JPEG) {
        L_WARNING("invalid compression type for bpp > 1\n", procName);
        comptype = IFF_TIFF_ZIP;
    }

    if ((tif = fopenTiffMemstream("tifferror", "w", pdata, psize)) == NULL)
        return ERROR_INT("tiff stream not opened", procName, 1);
    ret = pixWriteToTiffStream(tif, pix, comptype, natags, savals,
                               satypes, nasizes);

    TIFFClose(tif);
    return ret;
}

/* --------------------------------------------*/
#endif  /* HAVE_LIBTIFF */
/* --------------------------------------------*/