summaryrefslogtreecommitdiff
blob: 89f39e567b5d641c3c548b52d194622e5a4fa814 (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
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
/*====================================================================*
 -  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 pix2.c
 * <pre>
 *
 *    This file has these basic operations:
 *
 *      (1) Get and set: individual pixels, full image, rectangular region,
 *          pad pixels, border pixels, and color components for RGB
 *      (2) Add and remove border pixels
 *      (3) Endian byte swaps
 *      (4) Simple method for byte-processing images (instead of words)
 *
 *      Pixel poking
 *           l_int32     pixGetPixel()
 *           l_int32     pixSetPixel()
 *           l_int32     pixGetRGBPixel()
 *           l_int32     pixSetRGBPixel()
 *           l_int32     pixSetCmapPixel()
 *           l_int32     pixGetRandomPixel()
 *           l_int32     pixClearPixel()
 *           l_int32     pixFlipPixel()
 *           void        setPixelLow()
 *
 *      Find black or white value
 *           l_int32     pixGetBlackOrWhiteVal()
 *
 *      Full image clear/set/set-to-arbitrary-value
 *           l_int32     pixClearAll()
 *           l_int32     pixSetAll()
 *           l_int32     pixSetAllGray()
 *           l_int32     pixSetAllArbitrary()
 *           l_int32     pixSetBlackOrWhite()
 *           l_int32     pixSetComponentArbitrary()
 *
 *      Rectangular region clear/set/set-to-arbitrary-value/blend
 *           l_int32     pixClearInRect()
 *           l_int32     pixSetInRect()
 *           l_int32     pixSetInRectArbitrary()
 *           l_int32     pixBlendInRect()
 *
 *      Set pad bits
 *           l_int32     pixSetPadBits()
 *           l_int32     pixSetPadBitsBand()
 *
 *      Assign border pixels
 *           l_int32     pixSetOrClearBorder()
 *           l_int32     pixSetBorderVal()
 *           l_int32     pixSetBorderRingVal()
 *           l_int32     pixSetMirroredBorder()
 *           PIX        *pixCopyBorder()
 *
 *      Add and remove border
 *           PIX        *pixAddBorder()
 *           PIX        *pixAddBlackOrWhiteBorder()
 *           PIX        *pixAddBorderGeneral()
 *           PIX        *pixRemoveBorder()
 *           PIX        *pixRemoveBorderGeneral()
 *           PIX        *pixRemoveBorderToSize()
 *           PIX        *pixAddMirroredBorder()
 *           PIX        *pixAddRepeatedBorder()
 *           PIX        *pixAddMixedBorder()
 *           PIX        *pixAddContinuedBorder()
 *
 *      Helper functions using alpha
 *           l_int32     pixShiftAndTransferAlpha()
 *           PIX        *pixDisplayLayersRGBA()
 *
 *      Color sample setting and extraction
 *           PIX        *pixCreateRGBImage()
 *           PIX        *pixGetRGBComponent()
 *           l_int32     pixSetRGBComponent()
 *           PIX        *pixGetRGBComponentCmap()
 *           l_int32     pixCopyRGBComponent()
 *           l_int32     composeRGBPixel()
 *           l_int32     composeRGBAPixel()
 *           void        extractRGBValues()
 *           void        extractRGBAValues()
 *           l_int32     extractMinMaxComponent()
 *           l_int32     pixGetRGBLine()
 *
 *      Raster line pixel setter
 *           l_int32     setLineDataVal()
 *
 *      Conversion between big and little endians
 *           PIX        *pixEndianByteSwapNew()
 *           l_int32     pixEndianByteSwap()
 *           l_int32     lineEndianByteSwap()
 *           PIX        *pixEndianTwoByteSwapNew()
 *           l_int32     pixEndianTwoByteSwap()
 *
 *      Extract raster data as binary string
 *           l_int32     pixGetRasterData()
 *
 *      Test alpha component opaqueness
 *           l_int32     pixAlphaIsOpaque()
 *
 *      Infer resolution from image size
 *           l_int32     pixInferResolution()
 *
 *      Setup helpers for 8 bpp byte processing
 *           l_uint8   **pixSetupByteProcessing()
 *           l_int32     pixCleanupByteProcessing()
 *
 *      Setting parameters for antialias masking with alpha transforms
 *           void        l_setAlphaMaskBorder()
 * </pre>
 */

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

#include <string.h>
#include "allheaders.h"

static const l_uint32 rmask32[] = {0x0,
    0x00000001, 0x00000003, 0x00000007, 0x0000000f,
    0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
    0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff,
    0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff,
    0x0001ffff, 0x0003ffff, 0x0007ffff, 0x000fffff,
    0x001fffff, 0x003fffff, 0x007fffff, 0x00ffffff,
    0x01ffffff, 0x03ffffff, 0x07ffffff, 0x0fffffff,
    0x1fffffff, 0x3fffffff, 0x7fffffff, 0xffffffff};

    /* This is a global that determines the default 8 bpp alpha mask values
     * for rings at distance 1 and 2 from the border.  Declare extern
     * to use.  To change the values, use l_setAlphaMaskBorder(). */
LEPT_DLL l_float32  AlphaMaskBorderVals[2] = {0.0, 0.5};


#ifndef  NO_CONSOLE_IO
#define  DEBUG_SERIALIZE        0
#endif  /* ~NO_CONSOLE_IO */


/*-------------------------------------------------------------*
 *                         Pixel poking                        *
 *-------------------------------------------------------------*/
/*!
 * \brief   pixGetPixel()
 *
 * \param[in]    pix
 * \param[in]    x,y    pixel coords
 * \param[out]   pval   pixel value
 * \return  0 if OK; 1 or 2 on error
 *
 * <pre>
 * Notes:
 *      (1) This returns the value in the data array.  If the pix is
 *          colormapped, it returns the colormap index, not the rgb value.
 *      (2) Because of the function overhead and the parameter checking,
 *          this is much slower than using the GET_DATA_*() macros directly.
 *          Speed on a 1 Mpixel RGB image, using a 3 GHz machine:
 *            * pixGet/pixSet: ~25 Mpix/sec
 *            * GET_DATA/SET_DATA: ~350 MPix/sec
 *          If speed is important and you're doing random access into
 *          the pix, use pixGetLinePtrs() and the array access macros.
 *      (3) If the point is outside the image, this returns an error (2),
 *          with 0 in %pval.  To avoid spamming output, it fails silently.
 * </pre>
 */
l_ok
pixGetPixel(PIX       *pix,
            l_int32    x,
            l_int32    y,
            l_uint32  *pval)
{
l_int32    w, h, d, wpl, val;
l_uint32  *line, *data;

    PROCNAME("pixGetPixel");

    if (!pval)
        return ERROR_INT("&val not defined", procName, 1);
    *pval = 0;
    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);

    pixGetDimensions(pix, &w, &h, &d);
    if (x < 0 || x >= w || y < 0 || y >= h)
        return 2;

    wpl = pixGetWpl(pix);
    data = pixGetData(pix);
    line = data + y * wpl;
    switch (d)
    {
    case 1:
        val = GET_DATA_BIT(line, x);
        break;
    case 2:
        val = GET_DATA_DIBIT(line, x);
        break;
    case 4:
        val = GET_DATA_QBIT(line, x);
        break;
    case 8:
        val = GET_DATA_BYTE(line, x);
        break;
    case 16:
        val = GET_DATA_TWO_BYTES(line, x);
        break;
    case 32:
        val = line[x];
        break;
    default:
        return ERROR_INT("depth must be in {1,2,4,8,16,32} bpp", procName, 1);
    }

    *pval = val;
    return 0;
}


/*!
 * \brief   pixSetPixel()
 *
 * \param[in]    pix
 * \param[in]    x,y   pixel coords
 * \param[in]    val   value to be inserted
 * \return  0 if OK; 1 or 2 on error
 *
 * <pre>
 * Notes:
 *      (1) Warning: the input value is not checked for overflow with respect
 *          the the depth of %pix, and the sign bit (if any) is ignored.
 *          * For d == 1, %val > 0 sets the bit on.
 *          * For d == 2, 4, 8 and 16, %val is masked to the maximum allowable
 *            pixel value, and any (invalid) higher order bits are discarded.
 *      (2) See pixGetPixel() for information on performance.
 *      (3) If the point is outside the image, this returns an error (2),
 *          with 0 in %pval.  To avoid spamming output, it fails silently.
 * </pre>
 */
l_ok
pixSetPixel(PIX      *pix,
            l_int32   x,
            l_int32   y,
            l_uint32  val)
{
l_int32    w, h, d, wpl;
l_uint32  *line, *data;

    PROCNAME("pixSetPixel");

    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);
    pixGetDimensions(pix, &w, &h, &d);
    if (x < 0 || x >= w || y < 0 || y >= h)
        return 2;

    data = pixGetData(pix);
    wpl = pixGetWpl(pix);
    line = data + y * wpl;
    switch (d)
    {
    case 1:
        if (val)
            SET_DATA_BIT(line, x);
        else
            CLEAR_DATA_BIT(line, x);
        break;
    case 2:
        SET_DATA_DIBIT(line, x, val);
        break;
    case 4:
        SET_DATA_QBIT(line, x, val);
        break;
    case 8:
        SET_DATA_BYTE(line, x, val);
        break;
    case 16:
        SET_DATA_TWO_BYTES(line, x, val);
        break;
    case 32:
        line[x] = val;
        break;
    default:
        return ERROR_INT("depth must be in {1,2,4,8,16,32} bpp", procName, 1);
    }

    return 0;
}


/*!
 * \brief   pixGetRGBPixel()
 *
 * \param[in]    pix    32 bpp rgb, not colormapped
 * \param[in]    x,y    pixel coords
 * \param[out]   prval  [optional] red component
 * \param[out]   pgval  [optional] green component
 * \param[out]   pbval  [optional] blue component
 * \return  0 if OK; 1 or 2 on error
 *
 * <pre>
 * Notes:
 *      (1) If the point is outside the image, this returns an error (2),
 *          with 0 in %pval.  To avoid spamming output, it fails silently.
 * </pre>
 */
l_ok
pixGetRGBPixel(PIX      *pix,
               l_int32   x,
               l_int32   y,
               l_int32  *prval,
               l_int32  *pgval,
               l_int32  *pbval)
{
l_int32    w, h, d, wpl;
l_uint32  *data, *ppixel;

    PROCNAME("pixGetRGBPixel");

    if (prval) *prval = 0;
    if (pgval) *pgval = 0;
    if (pbval) *pbval = 0;
    if (!prval && !pgval && !pbval)
        return ERROR_INT("no output requested", procName, 1);
    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);
    pixGetDimensions(pix, &w, &h, &d);
    if (d != 32)
        return ERROR_INT("pix not 32 bpp", procName, 1);
    if (x < 0 || x >= w || y < 0 || y >= h)
        return 2;

    wpl = pixGetWpl(pix);
    data = pixGetData(pix);
    ppixel = data + y * wpl + x;
    if (prval) *prval = GET_DATA_BYTE(ppixel, COLOR_RED);
    if (pgval) *pgval = GET_DATA_BYTE(ppixel, COLOR_GREEN);
    if (pbval) *pbval = GET_DATA_BYTE(ppixel, COLOR_BLUE);
    return 0;
}


/*!
 * \brief   pixSetRGBPixel()
 *
 * \param[in]    pix    32 bpp rgb
 * \param[in]    x,y    pixel coords
 * \param[in]    rval   red component
 * \param[in]    gval   green component
 * \param[in]    bval   blue component
 * \return  0 if OK; 1 or 2 on error
 *
 * <pre>
 * Notes:
 *      (1) If the point is outside the image, this returns an error (2),
 *          and to avoid spamming output, it fails silently.
 * </pre>
 */
l_ok
pixSetRGBPixel(PIX     *pix,
               l_int32  x,
               l_int32  y,
               l_int32  rval,
               l_int32  gval,
               l_int32  bval)
{
l_int32    w, h, d, wpl;
l_uint32   pixel;
l_uint32  *data, *line;

    PROCNAME("pixSetRGBPixel");

    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);
    pixGetDimensions(pix, &w, &h, &d);
    if (d != 32)
        return ERROR_INT("pix not 32 bpp", procName, 1);
    if (x < 0 || x >= w || y < 0 || y >= h)
        return 2;

    wpl = pixGetWpl(pix);
    data = pixGetData(pix);
    line = data + y * wpl;
    composeRGBPixel(rval, gval, bval, &pixel);
    *(line + x) = pixel;
    return 0;
}


/*!
 * \brief   pixSetCmapPixel()
 *
 * \param[in]    pix    2, 4 or 8 bpp, colormapped
 * \param[in]    x,y    pixel coords
 * \param[in]    rval   red component
 * \param[in]    gval   green component
 * \param[in]    bval   blue component
 * \return  0 if OK; 1 or 2 on error
 *
 * <pre>
 * Notes:
 *      (1) If the point is outside the image, this returns an error (2),
 *          and to avoid spamming output, it fails silently.
 *      (2) - If the color already exists, use it.
 *          - If the color does not exist in the colormap, it is added
 *            if possible.
 *          - If there is not room in the colormap for the new color:
 *            * if d < 8, return 2 with a warning.
 *            * if d == 8, find and use the nearest color.
 *      (3) Note that this operation scales with the number of colors
 *          in the colormap, and therefore can be very expensive if an
 *          attempt is made to set many pixels.  (In that case, it should
 *          be implemented with a map:rgb-->index for efficiency.)
 *          This is best used with very small images.
 * </pre>
 */
l_ok
pixSetCmapPixel(PIX     *pix,
                l_int32  x,
                l_int32  y,
                l_int32  rval,
                l_int32  gval,
                l_int32  bval)
{
l_int32   w, h, d, index;
PIXCMAP  *cmap;

    PROCNAME("pixSetCmapPixel");

    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);
    if ((cmap = pixGetColormap(pix)) == NULL)
        return ERROR_INT("pix is not colormapped", procName, 1);
    pixGetDimensions(pix, &w, &h, &d);
    if (d != 2 && d != 4 && d != 8)
        return ERROR_INT("pix depth not 2, 4 or 8", procName, 1);
    if (x < 0 || x >= w || y < 0 || y >= h)
        return 2;

    if (d == 8) {  /* always add */
        pixcmapAddNearestColor(cmap, rval, gval, bval, &index);
    } else {  /* d < 8 */
        if (pixcmapAddNewColor(cmap, rval, gval, bval, &index) == 2)
            return ERROR_INT("colormap is full", procName, 2);
    }
    pixSetPixel(pix, x, y, index);
    return 0;
}


/*!
 * \brief   pixGetRandomPixel()
 *
 * \param[in]    pix    any depth; can be colormapped
 * \param[out]   pval   [optional] pixel value
 * \param[out]   px     [optional] x coordinate chosen; can be null
 * \param[out]   py     [optional] y coordinate chosen; can be null
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) If the pix is colormapped, it returns the rgb value.
 * </pre>
 */
l_ok
pixGetRandomPixel(PIX       *pix,
                  l_uint32  *pval,
                  l_int32   *px,
                  l_int32   *py)
{
l_int32   w, h, x, y, rval, gval, bval;
l_uint32  val;
PIXCMAP  *cmap;

    PROCNAME("pixGetRandomPixel");

    if (pval) *pval = 0;
    if (px) *px = 0;
    if (py) *py = 0;
    if (!pval && !px && !py)
        return ERROR_INT("no output requested", procName, 1);
    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);

    pixGetDimensions(pix, &w, &h, NULL);
    x = rand() % w;
    y = rand() % h;
    if (px) *px = x;
    if (py) *py = y;
    if (pval) {
        pixGetPixel(pix, x, y, &val);
        if ((cmap = pixGetColormap(pix)) != NULL) {
            pixcmapGetColor(cmap, val, &rval, &gval, &bval);
            composeRGBPixel(rval, gval, bval, pval);
        } else {
            *pval = val;
        }
    }

    return 0;
}


/*!
 * \brief   pixClearPixel()
 *
 * \param[in]    pix   any depth; warning if colormapped
 * \param[in]    x,y   pixel coords
 * \return  0 if OK; 1 or 2 on error.
 *
 * <pre>
 * Notes:
 *      (1) If the point is outside the image, this returns an error (2),
 *          with 0 in %pval.  To avoid spamming output, it fails silently.
 * </pre>
 */
l_ok
pixClearPixel(PIX     *pix,
              l_int32  x,
              l_int32  y)
{
l_int32    w, h, d, wpl;
l_uint32  *line, *data;

    PROCNAME("pixClearPixel");

    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);
    if (pixGetColormap(pix))
        L_WARNING("cmapped: setting to 0 may not be intended\n", procName);
    pixGetDimensions(pix, &w, &h, &d);
    if (x < 0 || x >= w || y < 0 || y >= h)
        return 2;

    wpl = pixGetWpl(pix);
    data = pixGetData(pix);
    line = data + y * wpl;
    switch (d)
    {
    case 1:
        CLEAR_DATA_BIT(line, x);
        break;
    case 2:
        CLEAR_DATA_DIBIT(line, x);
        break;
    case 4:
        CLEAR_DATA_QBIT(line, x);
        break;
    case 8:
        SET_DATA_BYTE(line, x, 0);
        break;
    case 16:
        SET_DATA_TWO_BYTES(line, x, 0);
        break;
    case 32:
        line[x] = 0;
        break;
    default:
        return ERROR_INT("depth must be in {1,2,4,8,16,32} bpp", procName, 1);
    }

    return 0;
}


/*!
 * \brief   pixFlipPixel()
 *
 * \param[in]    pix   any depth, warning if colormapped
 * \param[in]    x,y   pixel coords
 * \return  0 if OK; 1 or 2 on error
 *
 * <pre>
 * Notes:
 *      (1) If the point is outside the image, this returns an error (2),
 *          with 0 in %pval.  To avoid spamming output, it fails silently.
 * </pre>
 */
l_ok
pixFlipPixel(PIX     *pix,
             l_int32  x,
             l_int32  y)
{
l_int32    w, h, d, wpl;
l_uint32   val;
l_uint32  *line, *data;

    PROCNAME("pixFlipPixel");

    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);
    if (pixGetColormap(pix))
        L_WARNING("cmapped: setting to 0 may not be intended\n", procName);
    pixGetDimensions(pix, &w, &h, &d);
    if (x < 0 || x >= w || y < 0 || y >= h)
        return 2;

    data = pixGetData(pix);
    wpl = pixGetWpl(pix);
    line = data + y * wpl;
    switch (d)
    {
    case 1:
        val = GET_DATA_BIT(line, x);
        if (val)
            CLEAR_DATA_BIT(line, x);
        else
            SET_DATA_BIT(line, x);
        break;
    case 2:
        val = GET_DATA_DIBIT(line, x);
        val ^= 0x3;
        SET_DATA_DIBIT(line, x, val);
        break;
    case 4:
        val = GET_DATA_QBIT(line, x);
        val ^= 0xf;
        SET_DATA_QBIT(line, x, val);
        break;
    case 8:
        val = GET_DATA_BYTE(line, x);
        val ^= 0xff;
        SET_DATA_BYTE(line, x, val);
        break;
    case 16:
        val = GET_DATA_TWO_BYTES(line, x);
        val ^= 0xffff;
        SET_DATA_TWO_BYTES(line, x, val);
        break;
    case 32:
        val = line[x] ^ 0xffffffff;
        line[x] = val;
        break;
    default:
        return ERROR_INT("depth must be in {1,2,4,8,16,32} bpp", procName, 1);
    }

    return 0;
}


/*!
 * \brief   setPixelLow()
 *
 * \param[in]    line    ptr to beginning of line,
 * \param[in]    x       pixel location in line
 * \param[in]    depth   bpp
 * \param[in]    val     to be inserted
 * \return  void
 *
 * <pre>
 * Notes:
 *      (1) Caution: input variables are not checked!
 * </pre>
 */
void
setPixelLow(l_uint32  *line,
            l_int32    x,
            l_int32    depth,
            l_uint32   val)
{
    switch (depth)
    {
    case 1:
        if (val)
            SET_DATA_BIT(line, x);
        else
            CLEAR_DATA_BIT(line, x);
        break;
    case 2:
        SET_DATA_DIBIT(line, x, val);
        break;
    case 4:
        SET_DATA_QBIT(line, x, val);
        break;
    case 8:
        SET_DATA_BYTE(line, x, val);
        break;
    case 16:
        SET_DATA_TWO_BYTES(line, x, val);
        break;
    case 32:
        line[x] = val;
        break;
    default:
        lept_stderr("illegal depth in setPixelLow()\n");
    }
}


/*-------------------------------------------------------------*
 *                     Find black or white value               *
 *-------------------------------------------------------------*/
/*!
 * \brief   pixGetBlackOrWhiteVal()
 *
 * \param[in]    pixs    all depths; cmap ok
 * \param[in]    op      L_GET_BLACK_VAL, L_GET_WHITE_VAL
 * \param[out]   pval    pixel value
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Side effect.  For a colormapped image, if the requested
 *          color is not present and there is room to add it in the cmap,
 *          it is added and the new index is returned.  If there is no room,
 *          the index of the closest color in intensity is returned.
 * </pre>
 */
l_ok
pixGetBlackOrWhiteVal(PIX       *pixs,
                      l_int32    op,
                      l_uint32  *pval)
{
l_int32   d, val;
PIXCMAP  *cmap;

    PROCNAME("pixGetBlackOrWhiteVal");

    if (!pval)
        return ERROR_INT("&val not defined", procName, 1);
    *pval = 0;
    if (!pixs)
        return ERROR_INT("pixs not defined", procName, 1);
    if (op != L_GET_BLACK_VAL && op != L_GET_WHITE_VAL)
        return ERROR_INT("invalid op", procName, 1);

    cmap = pixGetColormap(pixs);
    d = pixGetDepth(pixs);
    if (!cmap) {
        if ((d == 1 && op == L_GET_WHITE_VAL) ||
            (d > 1 && op == L_GET_BLACK_VAL)) {  /* min val */
            val = 0;
        } else {  /* max val */
            val = (d == 32) ? 0xffffff00 : (1 << d) - 1;
        }
    } else {  /* handle colormap */
        if (op == L_GET_BLACK_VAL)
            pixcmapAddBlackOrWhite(cmap, 0, &val);
        else  /* L_GET_WHITE_VAL */
            pixcmapAddBlackOrWhite(cmap, 1, &val);
    }
    *pval = val;

    return 0;
}


/*-------------------------------------------------------------*
 *     Full image clear/set/set-to-arbitrary-value/invert      *
 *-------------------------------------------------------------*/
/*!
 * \brief   pixClearAll()
 *
 * \param[in]    pix    all depths; use cmapped with caution
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Clears all data to 0.  For 1 bpp, this is white; for grayscale
 *          or color, this is black.
 *      (2) Caution: for colormapped pix, this sets the color to the first
 *          one in the colormap.  Be sure that this is the intended color!
 * </pre>
 */
l_ok
pixClearAll(PIX  *pix)
{
    PROCNAME("pixClearAll");

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

    memset(pix->data, 0, 4LL * pix->wpl * pix->h);
    return 0;
}


/*!
 * \brief   pixSetAll()
 *
 * \param[in]    pix     all depths; use cmapped with caution
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Sets all data to 1.  For 1 bpp, this is black; for grayscale
 *          or color, this is white.
 *      (2) Caution: for colormapped pix, this sets the pixel value to the
 *          maximum value supported by the colormap: 2^d - 1.  However, this
 *          color may not be defined, because the colormap may not be full.
 * </pre>
 */
l_ok
pixSetAll(PIX  *pix)
{
l_int32   n;
PIXCMAP  *cmap;

    PROCNAME("pixSetAll");

    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);
    if ((cmap = pixGetColormap(pix)) != NULL) {
        n = pixcmapGetCount(cmap);
        if (n < cmap->nalloc)  /* cmap is not full */
            return ERROR_INT("cmap entry does not exist", procName, 1);
    }

    memset(pix->data, 0xff, 4LL * pix->wpl * pix->h);
    return 0;
}


/*!
 * \brief   pixSetAllGray()
 *
 * \param[in]    pix       all depths, cmap ok
 * \param[in]    grayval   in range 0 ... 255
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) N.B.  For all images, %grayval == 0 represents black and
 *          %grayval == 255 represents white.
 *      (2) For depth < 8, we do our best to approximate the gray level.
 *          For 1 bpp images, any %grayval < 128 is black; >= 128 is white.
 *          For 32 bpp images, each r,g,b component is set to %grayval,
 *          and the alpha component is preserved.
 *      (3) If pix is colormapped, it adds the gray value, replicated in
 *          all components, to the colormap if it's not there and there
 *          is room.  If the colormap is full, it finds the closest color in
 *          L2 distance of components.  This index is written to all pixels.
 * </pre>
 */
l_ok
pixSetAllGray(PIX     *pix,
              l_int32  grayval)
{
l_int32   d, spp, index;
l_uint32  val32;
PIX      *alpha;
PIXCMAP  *cmap;

    PROCNAME("pixSetAllGray");

    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);
    if (grayval < 0) {
        L_WARNING("grayval < 0; setting to 0\n", procName);
        grayval = 0;
    } else if (grayval > 255) {
        L_WARNING("grayval > 255; setting to 255\n", procName);
        grayval = 255;
    }

        /* Handle the colormap case */
    cmap = pixGetColormap(pix);
    if (cmap) {
        pixcmapAddNearestColor(cmap, grayval, grayval, grayval, &index);
        pixSetAllArbitrary(pix, index);
        return 0;
    }

        /* Non-cmapped */
    d = pixGetDepth(pix);
    spp = pixGetSpp(pix);
    if (d == 1) {
        if (grayval < 128)  /* black */
            pixSetAll(pix);
        else
            pixClearAll(pix);  /* white */
    } else if (d < 8) {
        grayval >>= 8 - d;
        pixSetAllArbitrary(pix, grayval);
    } else if (d == 8) {
        pixSetAllArbitrary(pix, grayval);
    } else if (d == 16) {
        grayval |= (grayval << 8);
        pixSetAllArbitrary(pix, grayval);
    } else if (d == 32 && spp == 3) {
        composeRGBPixel(grayval, grayval, grayval, &val32);
        pixSetAllArbitrary(pix, val32);
    } else if (d == 32 && spp == 4) {
        alpha = pixGetRGBComponent(pix, L_ALPHA_CHANNEL);
        composeRGBPixel(grayval, grayval, grayval, &val32);
        pixSetAllArbitrary(pix, val32);
        pixSetRGBComponent(pix, alpha, L_ALPHA_CHANNEL);
        pixDestroy(&alpha);
    } else {
        L_ERROR("invalid depth: %d\n", procName, d);
        return 1;
    }

    return 0;
}


/*!
 * \brief   pixSetAllArbitrary()
 *
 * \param[in]    pix    all depths; use cmapped with caution
 * \param[in]    val    value to set all pixels
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Caution 1!  For colormapped pix, %val is used as an index
 *          into a colormap.  Be sure that index refers to the intended color.
 *          If the color is not in the colormap, you should first add it
 *          and then call this function.
 *      (2) Caution 2!  For 32 bpp pix, the interpretation of the LSB
 *          of %val depends on whether spp == 3 (RGB) or spp == 4 (RGBA).
 *          For RGB, the LSB is ignored in image transformations.
 *          For RGBA, the LSB is interpreted as the alpha (transparency)
 *          component; full transparency has alpha == 0x0, whereas
 *          full opacity has alpha = 0xff.  An RGBA image with full
 *          opacity behaves like an RGB image.
 *      (3) As an example of (2), suppose you want to initialize a 32 bpp
 *          pix with partial opacity, say 0xee337788.  If the pix is 3 spp,
 *          the 0x88 alpha component will be ignored and may be changed
 *          in subsequent processing.  However, if the pix is 4 spp, the
 *          alpha component will be retained and used. The function
 *          pixCreate(w, h, 32) makes an RGB image by default, and
 *          pixSetSpp(pix, 4) can be used to promote an RGB image to RGBA.
 * </pre>
 */
l_ok
pixSetAllArbitrary(PIX      *pix,
                   l_uint32  val)
{
l_int32    n, i, j, w, h, d, wpl, npix;
l_uint32   maxval, wordval;
l_uint32  *data, *line;
PIXCMAP   *cmap;

    PROCNAME("pixSetAllArbitrary");

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

        /* If colormapped, make sure that val is less than the size
         * of the cmap array. */
    if ((cmap = pixGetColormap(pix)) != NULL) {
        n = pixcmapGetCount(cmap);
        if (val >= n) {
            L_WARNING("index not in colormap; using last color\n", procName);
            val = n - 1;
        }
    }

        /* Make sure val isn't too large for the pixel depth.
         * If it is too large, set the pixel color to white.  */
    pixGetDimensions(pix, &w, &h, &d);
    if (d < 32) {
        maxval = (1 << d) - 1;
        if (val > maxval) {
            L_WARNING("val = %d too large for depth; using maxval = %d\n",
                      procName, val, maxval);
            val = maxval;
        }
    }

        /* Set up word to tile with */
    wordval = 0;
    npix = 32 / d;    /* number of pixels per 32 bit word */
    for (j = 0; j < npix; j++)
        wordval |= (val << (j * d));
    wpl = pixGetWpl(pix);
    data = pixGetData(pix);
    for (i = 0; i < h; i++) {
        line = data + i * wpl;
        for (j = 0; j < wpl; j++) {
            *(line + j) = wordval;
        }
    }
    return 0;
}


/*!
 * \brief   pixSetBlackOrWhite()
 *
 * \param[in]    pixs    all depths; cmap ok
 * \param[in]    op      L_SET_BLACK, L_SET_WHITE
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Function for setting all pixels in an image to either black
 *          or white.
 *      (2) If pixs is colormapped, it adds black or white to the
 *          colormap if it's not there and there is room.  If the colormap
 *          is full, it finds the closest color in intensity.
 *          This index is written to all pixels.
 * </pre>
 */
l_ok
pixSetBlackOrWhite(PIX     *pixs,
                   l_int32  op)
{
l_int32   d, index;
PIXCMAP  *cmap;

    PROCNAME("pixSetBlackOrWhite");

    if (!pixs)
        return ERROR_INT("pix not defined", procName, 1);
    if (op != L_SET_BLACK && op != L_SET_WHITE)
        return ERROR_INT("invalid op", procName, 1);

    cmap = pixGetColormap(pixs);
    d = pixGetDepth(pixs);
    if (!cmap) {
        if ((d == 1 && op == L_SET_BLACK) || (d > 1 && op == L_SET_WHITE))
            pixSetAll(pixs);
        else
            pixClearAll(pixs);
    } else {  /* handle colormap */
        if (op == L_SET_BLACK)
            pixcmapAddBlackOrWhite(cmap, 0, &index);
        else  /* L_SET_WHITE */
            pixcmapAddBlackOrWhite(cmap, 1, &index);
        pixSetAllArbitrary(pixs, index);
    }

    return 0;
}


/*!
 * \brief   pixSetComponentArbitrary()
 *
 * \param[in]    pix    32 bpp
 * \param[in]    comp   COLOR_RED, COLOR_GREEN, COLOR_BLUE, L_ALPHA_CHANNEL
 * \param[in]    val    value to set this component
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) For example, this can be used to set the alpha component to opaque:
 *              pixSetComponentArbitrary(pix, L_ALPHA_CHANNEL, 255)
 * </pre>
 */
l_ok
pixSetComponentArbitrary(PIX     *pix,
                         l_int32  comp,
                         l_int32  val)
{
l_int32    i, nwords;
l_uint32   mask1, mask2;
l_uint32  *data;

    PROCNAME("pixSetComponentArbitrary");

    if (!pix || pixGetDepth(pix) != 32)
        return ERROR_INT("pix not defined or not 32 bpp", procName, 1);
    if (comp != COLOR_RED && comp != COLOR_GREEN && comp != COLOR_BLUE &&
        comp != L_ALPHA_CHANNEL)
        return ERROR_INT("invalid component", procName, 1);
    if (val < 0 || val > 255)
        return ERROR_INT("val not in [0 ... 255]", procName, 1);

    mask1 = ~(255 << (8 * (3 - comp)));
    mask2 = val << (8 * (3 - comp));
    nwords = pixGetHeight(pix) * pixGetWpl(pix);
    data = pixGetData(pix);
    for (i = 0; i < nwords; i++) {
        data[i] &= mask1;  /* clear out the component */
        data[i] |= mask2;  /* insert the new component value */
    }

    return 0;
}


/*-------------------------------------------------------------*
 *     Rectangular region clear/set/set-to-arbitrary-value     *
 *-------------------------------------------------------------*/
/*!
 * \brief   pixClearInRect()
 *
 * \param[in]    pix   all depths; can be cmapped
 * \param[in]    box   in which all pixels will be cleared
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Clears all data in rect to 0.  For 1 bpp, this is white;
 *          for grayscale or color, this is black.
 *      (2) Caution: for colormapped pix, this sets the color to the first
 *          one in the colormap.  Be sure that this is the intended color!
 * </pre>
 */
l_ok
pixClearInRect(PIX  *pix,
               BOX  *box)
{
l_int32  x, y, w, h;

    PROCNAME("pixClearInRect");

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

    boxGetGeometry(box, &x, &y, &w, &h);
    pixRasterop(pix, x, y, w, h, PIX_CLR, NULL, 0, 0);
    return 0;
}


/*!
 * \brief   pixSetInRect()
 *
 * \param[in]    pix   all depths, can be cmapped
 * \param[in]    box   in which all pixels will be set
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Sets all data in rect to 1.  For 1 bpp, this is black;
 *          for grayscale or color, this is white.
 *      (2) Caution: for colormapped pix, this sets the pixel value to the
 *          maximum value supported by the colormap: 2^d - 1.  However, this
 *          color may not be defined, because the colormap may not be full.
 * </pre>
 */
l_ok
pixSetInRect(PIX  *pix,
             BOX  *box)
{
l_int32   n, x, y, w, h;
PIXCMAP  *cmap;

    PROCNAME("pixSetInRect");

    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);
    if (!box)
        return ERROR_INT("box not defined", procName, 1);
    if ((cmap = pixGetColormap(pix)) != NULL) {
        n = pixcmapGetCount(cmap);
        if (n < cmap->nalloc)  /* cmap is not full */
            return ERROR_INT("cmap entry does not exist", procName, 1);
    }

    boxGetGeometry(box, &x, &y, &w, &h);
    pixRasterop(pix, x, y, w, h, PIX_SET, NULL, 0, 0);
    return 0;
}


/*!
 * \brief   pixSetInRectArbitrary()
 *
 * \param[in]    pix   all depths; can be cmapped
 * \param[in]    box   in which all pixels will be set to val
 * \param[in]    val   value to set all pixels
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) For colormapped pix, be sure the value is the intended
 *          one in the colormap.
 *      (2) Caution: for colormapped pix, this sets each pixel in the
 *          rect to the color at the index equal to val.  Be sure that
 *          this index exists in the colormap and that it is the intended one!
 * </pre>
 */
l_ok
pixSetInRectArbitrary(PIX      *pix,
                      BOX      *box,
                      l_uint32  val)
{
l_int32    n, x, y, xstart, xend, ystart, yend, bw, bh, w, h, d, wpl, maxval;
l_uint32  *data, *line;
BOX       *boxc;
PIXCMAP   *cmap;

    PROCNAME("pixSetInRectArbitrary");

    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);
    if (!box)
        return ERROR_INT("box not defined", procName, 1);
    pixGetDimensions(pix, &w, &h, &d);
    if (d != 1 && d != 2 && d != 4 && d !=8 && d != 16 && d != 32)
        return ERROR_INT("depth must be in {1,2,4,8,16,32} bpp", procName, 1);
    if ((cmap = pixGetColormap(pix)) != NULL) {
        n = pixcmapGetCount(cmap);
        if (val >= n) {
            L_WARNING("index not in colormap; using last color\n", procName);
            val = n - 1;
        }
    }

    maxval = (d == 32) ? 0xffffff00 : (1 << d) - 1;
    if (val > maxval) val = maxval;

        /* Handle the simple cases: the min and max values */
    if (val == 0) {
        pixClearInRect(pix, box);
        return 0;
    }
    if (d == 1 ||
        (d == 2 && val == 3) ||
        (d == 4 && val == 0xf) ||
        (d == 8 && val == 0xff) ||
        (d == 16 && val == 0xffff) ||
        (d == 32 && ((val ^ 0xffffff00) >> 8 == 0))) {
        pixSetInRect(pix, box);
        return 0;
    }

        /* Find the overlap of box with the input pix */
    if ((boxc = boxClipToRectangle(box, w, h)) == NULL)
        return ERROR_INT("no overlap of box with image", procName, 1);
    boxGetGeometry(boxc, &xstart, &ystart, &bw, &bh);
    xend = xstart + bw - 1;
    yend = ystart + bh - 1;
    boxDestroy(&boxc);

    wpl = pixGetWpl(pix);
    data = pixGetData(pix);
    for (y = ystart; y <= yend; y++) {
        line = data + y * wpl;
        for (x = xstart; x <= xend; x++) {
            switch(d)
            {
            case 2:
                SET_DATA_DIBIT(line, x, val);
                break;
            case 4:
                SET_DATA_QBIT(line, x, val);
                break;
            case 8:
                SET_DATA_BYTE(line, x, val);
                break;
            case 16:
                SET_DATA_TWO_BYTES(line, x, val);
                break;
            case 32:
                line[x] = val;
                break;
            default:
                return ERROR_INT("depth not 2|4|8|16|32 bpp", procName, 1);
            }
        }
    }

    return 0;
}


/*!
 * \brief   pixBlendInRect()
 *
 * \param[in]    pixs   32 bpp rgb
 * \param[in]    box    [optional] in which all pixels will be blended
 * \param[in]    val    blend value; 0xrrggbb00
 * \param[in]    fract  fraction of color to be blended with each pixel in pixs
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This is an in-place function.  It blends the input color %val
 *          with the pixels in pixs in the specified rectangle.
 *          If no rectangle is specified, it blends over the entire image.
 * </pre>
 */
l_ok
pixBlendInRect(PIX       *pixs,
               BOX       *box,
               l_uint32   val,
               l_float32  fract)
{
l_int32    i, j, bx, by, bw, bh, w, h, wpls;
l_int32    prval, pgval, pbval, rval, gval, bval;
l_uint32   val32;
l_uint32  *datas, *lines;

    PROCNAME("pixBlendInRect");

    if (!pixs || pixGetDepth(pixs) != 32)
        return ERROR_INT("pixs not defined or not 32 bpp", procName, 1);

    extractRGBValues(val, &rval, &gval, &bval);
    pixGetDimensions(pixs, &w, &h, NULL);
    datas = pixGetData(pixs);
    wpls = pixGetWpl(pixs);
    if (!box) {
        for (i = 0; i < h; i++) {   /* scan over box */
            lines = datas +  i * wpls;
            for (j = 0; j < w; j++) {
                val32 = *(lines + j);
                extractRGBValues(val32, &prval, &pgval, &pbval);
                prval = (l_int32)((1. - fract) * prval + fract * rval);
                pgval = (l_int32)((1. - fract) * pgval + fract * gval);
                pbval = (l_int32)((1. - fract) * pbval + fract * bval);
                composeRGBPixel(prval, pgval, pbval, &val32);
                *(lines + j) = val32;
            }
        }
        return 0;
    }

    boxGetGeometry(box, &bx, &by, &bw, &bh);
    for (i = 0; i < bh; i++) {   /* scan over box */
        if (by + i < 0 || by + i >= h) continue;
        lines = datas + (by + i) * wpls;
        for (j = 0; j < bw; j++) {
            if (bx + j < 0 || bx + j >= w) continue;
            val32 = *(lines + bx + j);
            extractRGBValues(val32, &prval, &pgval, &pbval);
            prval = (l_int32)((1. - fract) * prval + fract * rval);
            pgval = (l_int32)((1. - fract) * pgval + fract * gval);
            pbval = (l_int32)((1. - fract) * pbval + fract * bval);
            composeRGBPixel(prval, pgval, pbval, &val32);
            *(lines + bx + j) = val32;
        }
    }
    return 0;
}


/*-------------------------------------------------------------*
 *                         Set pad bits                        *
 *-------------------------------------------------------------*/
/*!
 * \brief   pixSetPadBits()
 *
 * \param[in]    pix   1, 2, 4, 8, 16, 32 bpp
 * \param[in]    val   0 or 1
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) The pad bits are the bits that expand each scanline to a
 *          multiple of 32 bits.  They are usually not used in
 *          image processing operations.  When boundary conditions
 *          are important, as in seedfill, they must be set properly.
 *      (2) This sets the value of the pad bits (if any) in the last
 *          32-bit word in each scanline.
 *      (3) For 32 bpp pix, there are no pad bits, so this is a no-op.
 *      (4) When writing formatted output, such as tiff, png or jpeg,
 *          the pad bits have no effect on the raster image that is
 *          generated by reading back from the file.  However, in some
 *          cases, the compressed file itself will depend on the pad
 *          bits.  This is seen, for example, in Windows with 2 and 4 bpp
 *          tiff-compressed images that have pad bits on each scanline.
 *          It is sometimes convenient to use a golden file with a
 *          byte-by-byte check to verify invariance.  Consequently,
 *          and because setting the pad bits is cheap, the pad bits are
 *          set to 0 before writing these compressed files.
 * </pre>
 */
l_ok
pixSetPadBits(PIX     *pix,
              l_int32  val)
{
l_int32    i, w, h, d, wpl, endbits, fullwords;
l_uint32   mask;
l_uint32  *data, *pword;

    PROCNAME("pixSetPadBits");

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

    pixGetDimensions(pix, &w, &h, &d);
    if (d == 32)  /* no padding exists for 32 bpp */
        return 0;

    data = pixGetData(pix);
    wpl = pixGetWpl(pix);
    endbits = 32 - (((l_int64)w * d) % 32);
    if (endbits == 32)  /* no partial word */
        return 0;
    fullwords = (1LL * w * d) / 32;
    mask = rmask32[endbits];
    if (val == 0)
        mask = ~mask;

    for (i = 0; i < h; i++) {
        pword = data + i * wpl + fullwords;
        if (val == 0) /* clear */
            *pword = *pword & mask;
        else  /* set */
            *pword = *pword | mask;
    }

    return 0;
}


/*!
 * \brief   pixSetPadBitsBand()
 *
 * \param[in]    pix   1, 2, 4, 8, 16, 32 bpp
 * \param[in]    by    starting y value of band
 * \param[in]    bh    height of band
 * \param[in]    val   0 or 1
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) The pad bits are the bits that expand each scanline to a
 *          multiple of 32 bits.  They are usually not used in
 *          image processing operations.  When boundary conditions
 *          are important, as in seedfill, they must be set properly.
 *      (2) This sets the value of the pad bits (if any) in the last
 *          32-bit word in each scanline, within the specified
 *          band of raster lines.
 *      (3) For 32 bpp pix, there are no pad bits, so this is a no-op.
 * </pre>
 */
l_ok
pixSetPadBitsBand(PIX     *pix,
                  l_int32  by,
                  l_int32  bh,
                  l_int32  val)
{
l_int32    i, w, h, d, wpl, endbits, fullwords;
l_uint32   mask;
l_uint32  *data, *pword;

    PROCNAME("pixSetPadBitsBand");

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

    pixGetDimensions(pix, &w, &h, &d);
    if (d == 32)  /* no padding exists for 32 bpp */
        return 0;

    if (by < 0)
        by = 0;
    if (by >= h)
        return ERROR_INT("start y not in image", procName, 1);
    if (by + bh > h)
        bh = h - by;

    data = pixGetData(pix);
    wpl = pixGetWpl(pix);
    endbits = 32 - (((l_int64)w * d) % 32);
    if (endbits == 32)  /* no partial word */
        return 0;
    fullwords = (l_int64)w * d / 32;

    mask = rmask32[endbits];
    if (val == 0)
        mask = ~mask;

    for (i = by; i < by + bh; i++) {
        pword = data + i * wpl + fullwords;
        if (val == 0) /* clear */
            *pword = *pword & mask;
        else  /* set */
            *pword = *pword | mask;
    }

    return 0;
}


/*-------------------------------------------------------------*
 *                       Set border pixels                     *
 *-------------------------------------------------------------*/
/*!
 * \brief   pixSetOrClearBorder()
 *
 * \param[in]    pixs   all depths
 * \param[in]    left,  right, top, bot amount to set or clear
 * \param[in]    op     operation PIX_SET or PIX_CLR
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) The border region is defined to be the region in the
 *          image within a specific distance of each edge.  Here, we
 *          allow the pixels within a specified distance of each
 *          edge to be set independently.  This either sets or
 *          clears all pixels in the border region.
 *      (2) For binary images, use PIX_SET for black and PIX_CLR for white.
 *      (3) For grayscale or color images, use PIX_SET for white
 *          and PIX_CLR for black.
 * </pre>
 */
l_ok
pixSetOrClearBorder(PIX     *pixs,
                    l_int32  left,
                    l_int32  right,
                    l_int32  top,
                    l_int32  bot,
                    l_int32  op)
{
l_int32  w, h;

    PROCNAME("pixSetOrClearBorder");

    if (!pixs)
        return ERROR_INT("pixs not defined", procName, 1);
    if (op != PIX_SET && op != PIX_CLR)
        return ERROR_INT("op must be PIX_SET or PIX_CLR", procName, 1);

    pixGetDimensions(pixs, &w, &h, NULL);
    pixRasterop(pixs, 0, 0, left, h, op, NULL, 0, 0);
    pixRasterop(pixs, w - right, 0, right, h, op, NULL, 0, 0);
    pixRasterop(pixs, 0, 0, w, top, op, NULL, 0, 0);
    pixRasterop(pixs, 0, h - bot, w, bot, op, NULL, 0, 0);

    return 0;
}


/*!
 * \brief   pixSetBorderVal()
 *
 * \param[in]    pixs                   8, 16 or 32 bpp
 * \param[in]    left, right, top, bot  amount to set
 * \param[in]    val                    value to set at each border pixel
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) The border region is defined to be the region in the
 *          image within a specific distance of each edge.  Here, we
 *          allow the pixels within a specified distance of each
 *          edge to be set independently.  This sets the pixels
 *          in the border region to the given input value.
 *      (2) For efficiency, use pixSetOrClearBorder() if
 *          you're setting the border to either black or white.
 *      (3) If d != 32, the input value should be masked off
 *          to the appropriate number of least significant bits.
 *      (4) The code is easily generalized for 2 or 4 bpp.
 * </pre>
 */
l_ok
pixSetBorderVal(PIX      *pixs,
                l_int32   left,
                l_int32   right,
                l_int32   top,
                l_int32   bot,
                l_uint32  val)
{
l_int32    w, h, d, wpls, i, j, bstart, rstart;
l_uint32  *datas, *lines;

    PROCNAME("pixSetBorderVal");

    if (!pixs)
        return ERROR_INT("pixs not defined", procName, 1);
    pixGetDimensions(pixs, &w, &h, &d);
    if (d != 8 && d != 16 && d != 32)
        return ERROR_INT("depth must be 8, 16 or 32 bpp", procName, 1);

    datas = pixGetData(pixs);
    wpls = pixGetWpl(pixs);
    if (d == 8) {
        val &= 0xff;
        for (i = 0; i < top; i++) {
            lines = datas + i * wpls;
            for (j = 0; j < w; j++)
                SET_DATA_BYTE(lines, j, val);
        }
        rstart = w - right;
        bstart = h - bot;
        for (i = top; i < bstart; i++) {
            lines = datas + i * wpls;
            for (j = 0; j < left; j++)
                SET_DATA_BYTE(lines, j, val);
            for (j = rstart; j < w; j++)
                SET_DATA_BYTE(lines, j, val);
        }
        for (i = bstart; i < h; i++) {
            lines = datas + i * wpls;
            for (j = 0; j < w; j++)
                SET_DATA_BYTE(lines, j, val);
        }
    } else if (d == 16) {
        val &= 0xffff;
        for (i = 0; i < top; i++) {
            lines = datas + i * wpls;
            for (j = 0; j < w; j++)
                SET_DATA_TWO_BYTES(lines, j, val);
        }
        rstart = w - right;
        bstart = h - bot;
        for (i = top; i < bstart; i++) {
            lines = datas + i * wpls;
            for (j = 0; j < left; j++)
                SET_DATA_TWO_BYTES(lines, j, val);
            for (j = rstart; j < w; j++)
                SET_DATA_TWO_BYTES(lines, j, val);
        }
        for (i = bstart; i < h; i++) {
            lines = datas + i * wpls;
            for (j = 0; j < w; j++)
                SET_DATA_TWO_BYTES(lines, j, val);
        }
    } else {   /* d == 32 */
        for (i = 0; i < top; i++) {
            lines = datas + i * wpls;
            for (j = 0; j < w; j++)
                *(lines + j) = val;
        }
        rstart = w - right;
        bstart = h - bot;
        for (i = top; i < bstart; i++) {
            lines = datas + i * wpls;
            for (j = 0; j < left; j++)
                *(lines + j) = val;
            for (j = rstart; j < w; j++)
                *(lines + j) = val;
        }
        for (i = bstart; i < h; i++) {
            lines = datas + i * wpls;
            for (j = 0; j < w; j++)
                *(lines + j) = val;
        }
    }

    return 0;
}


/*!
 * \brief   pixSetBorderRingVal()
 *
 * \param[in]    pixs    any depth; cmap OK
 * \param[in]    dist    distance from outside; must be > 0; first ring is 1
 * \param[in]    val     value to set at each border pixel
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) The rings are single-pixel-wide rectangular sets of
 *          pixels at a given distance from the edge of the pix.
 *          This sets all pixels in a given ring to a value.
 * </pre>
 */
l_ok
pixSetBorderRingVal(PIX      *pixs,
                    l_int32   dist,
                    l_uint32  val)
{
l_int32  w, h, d, i, j, xend, yend;

    PROCNAME("pixSetBorderRingVal");

    if (!pixs)
        return ERROR_INT("pixs not defined", procName, 1);
    if (dist < 1)
        return ERROR_INT("dist must be > 0", procName, 1);
    pixGetDimensions(pixs, &w, &h, &d);
    if (w < 2 * dist + 1 || h < 2 * dist + 1)
        return ERROR_INT("ring doesn't exist", procName, 1);
    if (d < 32 && (val >= (1 << d)))
        return ERROR_INT("invalid pixel value", procName, 1);

    xend = w - dist;
    yend = h - dist;
    for (j = dist - 1; j <= xend; j++)
        pixSetPixel(pixs, j, dist - 1, val);
    for (j = dist - 1; j <= xend; j++)
        pixSetPixel(pixs, j, yend, val);
    for (i = dist - 1; i <= yend; i++)
        pixSetPixel(pixs, dist - 1, i, val);
    for (i = dist - 1; i <= yend; i++)
        pixSetPixel(pixs, xend, i, val);

    return 0;
}


/*!
 * \brief   pixSetMirroredBorder()
 *
 * \param[in]    pixs                   all depths; colormap ok
 * \param[in]    left, right, top, bot  number of pixels to set
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This applies what is effectively mirror boundary conditions
 *          to a border region in the image.  It is in-place.
 *      (2) This is useful for setting pixels near the border to a
 *          value representative of the near pixels to the interior.
 *      (3) The general pixRasterop() is used for an in-place operation here
 *          because there is no overlap between the src and dest rectangles.
 * </pre>
 */
l_ok
pixSetMirroredBorder(PIX     *pixs,
                     l_int32  left,
                     l_int32  right,
                     l_int32  top,
                     l_int32  bot)
{
l_int32  i, j, w, h;

    PROCNAME("pixSetMirroredBorder");

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

    pixGetDimensions(pixs, &w, &h, NULL);
    for (j = 0; j < left; j++)
        pixRasterop(pixs, left - 1 - j, top, 1, h - top - bot, PIX_SRC,
                    pixs, left + j, top);
    for (j = 0; j < right; j++)
        pixRasterop(pixs, w - right + j, top, 1, h - top - bot, PIX_SRC,
                    pixs, w - right - 1 - j, top);
    for (i = 0; i < top; i++)
        pixRasterop(pixs, 0, top - 1 - i, w, 1, PIX_SRC,
                    pixs, 0, top + i);
    for (i = 0; i < bot; i++)
        pixRasterop(pixs, 0, h - bot + i, w, 1, PIX_SRC,
                    pixs, 0, h - bot - 1 - i);

    return 0;
}


/*!
 * \brief   pixCopyBorder()
 *
 * \param[in]    pixd                   all depths; colormap ok; can be NULL
 * \param[in]    pixs                   same depth and size as pixd
 * \param[in]    left, right, top, bot  number of pixels to copy
 * \return  pixd, or NULL on error if pixd is not defined
 *
 * <pre>
 * Notes:
 *      (1) pixd can be null, but otherwise it must be the same size
 *          and depth as pixs.  Always returns pixd.
 *      (2) This is useful in situations where by setting a few border
 *          pixels we can avoid having to copy all pixels in pixs into
 *          pixd as an initialization step for some operation.
 *          Nevertheless, for safety, if making a new pixd, all the
 *          non-border pixels are initialized to 0.
 * </pre>
 */
PIX *
pixCopyBorder(PIX     *pixd,
              PIX     *pixs,
              l_int32  left,
              l_int32  right,
              l_int32  top,
              l_int32  bot)
{
l_int32  w, h;

    PROCNAME("pixCopyBorder");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, pixd);

    if (pixd) {
        if (pixd == pixs) {
            L_WARNING("same: nothing to do\n", procName);
            return pixd;
        } else if (!pixSizesEqual(pixs, pixd)) {
            return (PIX *)ERROR_PTR("pixs and pixd sizes differ",
                                    procName, pixd);
        }
    } else {
        if ((pixd = pixCreateTemplate(pixs)) == NULL)
            return (PIX *)ERROR_PTR("pixd not made", procName, pixd);
    }

    pixGetDimensions(pixs, &w, &h, NULL);
    pixRasterop(pixd, 0, 0, left, h, PIX_SRC, pixs, 0, 0);
    pixRasterop(pixd, w - right, 0, right, h, PIX_SRC, pixs, w - right, 0);
    pixRasterop(pixd, 0, 0, w, top, PIX_SRC, pixs, 0, 0);
    pixRasterop(pixd, 0, h - bot, w, bot, PIX_SRC, pixs, 0, h - bot);
    return pixd;
}



/*-------------------------------------------------------------*
 *                     Add and remove border                   *
 *-------------------------------------------------------------*/
/*!
 * \brief   pixAddBorder()
 *
 * \param[in]    pixs   all depths; colormap ok
 * \param[in]    npix   number of pixels to be added to each side
 * \param[in]    val    value of added border pixels
 * \return  pixd with the added exterior pixels, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) See pixGetBlackOrWhiteVal() for values of black and white pixels.
 * </pre>
 */
PIX *
pixAddBorder(PIX      *pixs,
             l_int32   npix,
             l_uint32  val)
{
    PROCNAME("pixAddBorder");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
    if (npix == 0)
        return pixClone(pixs);
    return pixAddBorderGeneral(pixs, npix, npix, npix, npix, val);
}


/*!
 * \brief   pixAddBlackOrWhiteBorder()
 *
 * \param[in]    pixs all depths; colormap ok
 * \param[in]    left, right, top, bot  number of pixels added
 * \param[in]    op L_GET_BLACK_VAL, L_GET_WHITE_VAL
 * \return  pixd with the added exterior pixels, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) See pixGetBlackOrWhiteVal() for possible side effect (adding
 *          a color to a colormap).
 *      (2) The only complication is that pixs may have a colormap.
 *          There are two ways to add the black or white border:
 *          (a) As done here (simplest, most efficient)
 *          (b) l_int32 ws, hs, d;
 *              pixGetDimensions(pixs, &ws, &hs, &d);
 *              Pix *pixd = pixCreate(ws + left + right, hs + top + bot, d);
 *              PixColormap *cmap = pixGetColormap(pixs);
 *              if (cmap != NULL)
 *                  pixSetColormap(pixd, pixcmapCopy(cmap));
 *              pixSetBlackOrWhite(pixd, L_SET_WHITE);  // uses cmap
 *              pixRasterop(pixd, left, top, ws, hs, PIX_SET, pixs, 0, 0);
 * </pre>
 */
PIX *
pixAddBlackOrWhiteBorder(PIX     *pixs,
                         l_int32  left,
                         l_int32  right,
                         l_int32  top,
                         l_int32  bot,
                         l_int32  op)
{
l_uint32  val;

    PROCNAME("pixAddBlackOrWhiteBorder");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
    if (op != L_GET_BLACK_VAL && op != L_GET_WHITE_VAL)
        return (PIX *)ERROR_PTR("invalid op", procName, NULL);

    pixGetBlackOrWhiteVal(pixs, op, &val);
    return pixAddBorderGeneral(pixs, left, right, top, bot, val);
}


/*!
 * \brief   pixAddBorderGeneral()
 *
 * \param[in]    pixs                   all depths; colormap ok
 * \param[in]    left, right, top, bot  number of pixels added
 * \param[in]    val                    value of added border pixels
 * \return  pixd with the added exterior pixels, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) For binary images:
 *             white:  val = 0
 *             black:  val = 1
 *          For grayscale images:
 *             white:  val = 2 ** d - 1
 *             black:  val = 0
 *          For rgb color images:
 *             white:  val = 0xffffff00
 *             black:  val = 0
 *          For colormapped images, set val to the appropriate colormap index.
 *      (2) If the added border is either black or white, you can use
 *             pixAddBlackOrWhiteBorder()
 *          The black and white values for all images can be found with
 *             pixGetBlackOrWhiteVal()
 *          which, if pixs is cmapped, may add an entry to the colormap.
 *          Alternatively, if pixs has a colormap, you can find the index
 *          of the pixel whose intensity is closest to white or black:
 *             white: pixcmapGetRankIntensity(cmap, 1.0, &index);
 *             black: pixcmapGetRankIntensity(cmap, 0.0, &index);
 *          and use that for val.
 * </pre>
 */
PIX *
pixAddBorderGeneral(PIX      *pixs,
                    l_int32   left,
                    l_int32   right,
                    l_int32   top,
                    l_int32   bot,
                    l_uint32  val)
{
l_int32  ws, hs, wd, hd, d, maxval, op;
PIX     *pixd;

    PROCNAME("pixAddBorderGeneral");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
    if (left < 0 || right < 0 || top < 0 || bot < 0)
        return (PIX *)ERROR_PTR("negative border added!", procName, NULL);

    pixGetDimensions(pixs, &ws, &hs, &d);
    wd = ws + left + right;
    hd = hs + top + bot;
    if ((pixd = pixCreate(wd, hd, d)) == NULL)
        return (PIX *)ERROR_PTR("pixd not made", procName, NULL);
    pixCopyResolution(pixd, pixs);
    pixCopyColormap(pixd, pixs);

        /* Set the new border pixels */
    maxval = (d == 32) ? 0xffffff00 : (1 << d) - 1;
    op = UNDEF;
    if (val == 0)
        op = PIX_CLR;
    else if (val >= maxval)
        op = PIX_SET;
    if (op == UNDEF) {
        pixSetAllArbitrary(pixd, val);
    } else {  /* just set or clear the border pixels */
        pixRasterop(pixd, 0, 0, left, hd, op, NULL, 0, 0);
        pixRasterop(pixd, wd - right, 0, right, hd, op, NULL, 0, 0);
        pixRasterop(pixd, 0, 0, wd, top, op, NULL, 0, 0);
        pixRasterop(pixd, 0, hd - bot, wd, bot, op, NULL, 0, 0);
    }

        /* Copy pixs into the interior */
    pixRasterop(pixd, left, top, ws, hs, PIX_SRC, pixs, 0, 0);
    return pixd;
}


/*!
 * \brief   pixRemoveBorder()
 *
 * \param[in]    pixs   all depths; colormap ok
 * \param[in]    npix   number to be removed from each of the 4 sides
 * \return  pixd with pixels removed around border, or NULL on error
 */
PIX *
pixRemoveBorder(PIX     *pixs,
                l_int32  npix)
{
    PROCNAME("pixRemoveBorder");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
    if (npix == 0)
        return pixClone(pixs);
    return pixRemoveBorderGeneral(pixs, npix, npix, npix, npix);
}


/*!
 * \brief   pixRemoveBorderGeneral()
 *
 * \param[in]    pixs                   all depths; colormap ok
 * \param[in]    left, right, top, bot  number of pixels removed
 * \return  pixd with pixels removed around border, or NULL on error
 */
PIX *
pixRemoveBorderGeneral(PIX     *pixs,
                       l_int32  left,
                       l_int32  right,
                       l_int32  top,
                       l_int32  bot)
{
l_int32  ws, hs, wd, hd, d;
PIX     *pixd;

    PROCNAME("pixRemoveBorderGeneral");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
    if (left < 0 || right < 0 || top < 0 || bot < 0)
        return (PIX *)ERROR_PTR("negative border removed!", procName, NULL);

    pixGetDimensions(pixs, &ws, &hs, &d);
    wd = ws - left - right;
    hd = hs - top - bot;
    if (wd <= 0)
        return (PIX *)ERROR_PTR("width must be > 0", procName, NULL);
    if (hd <= 0)
        return (PIX *)ERROR_PTR("height must be > 0", procName, NULL);
    if ((pixd = pixCreate(wd, hd, d)) == NULL)
        return (PIX *)ERROR_PTR("pixd not made", procName, NULL);
    pixCopyResolution(pixd, pixs);
    pixCopySpp(pixd, pixs);
    pixCopyColormap(pixd, pixs);

    pixRasterop(pixd, 0, 0, wd, hd, PIX_SRC, pixs, left, top);
    if (pixGetDepth(pixs) == 32 && pixGetSpp(pixs) == 4)
        pixShiftAndTransferAlpha(pixd, pixs, -left, -top);
    return pixd;
}


/*!
 * \brief   pixRemoveBorderToSize()
 *
 * \param[in]    pixs   all depths; colormap ok
 * \param[in]    wd     target width; use 0 if only removing from height
 * \param[in]    hd     target height; use 0 if only removing from width
 * \return  pixd with pixels removed around border, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) Removes pixels as evenly as possible from the sides of the
 *          image, leaving the central part.
 *      (2) Returns clone if no pixels requested removed, or the target
 *          sizes are larger than the image.
 * </pre>
 */
PIX *
pixRemoveBorderToSize(PIX     *pixs,
                      l_int32  wd,
                      l_int32  hd)
{
l_int32  w, h, top, bot, left, right, delta;

    PROCNAME("pixRemoveBorderToSize");

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

    pixGetDimensions(pixs, &w, &h, NULL);
    if ((wd <= 0 || wd >= w) && (hd <= 0 || hd >= h))
        return pixClone(pixs);

    left = right = (w - wd) / 2;
    delta = w - 2 * left - wd;
    right += delta;
    top = bot = (h - hd) / 2;
    delta = h - hd - 2 * top;
    bot += delta;
    if (wd <= 0 || wd > w)
        left = right = 0;
    else if (hd <= 0 || hd > h)
        top = bot = 0;

    return pixRemoveBorderGeneral(pixs, left, right, top, bot);
}


/*!
 * \brief   pixAddMirroredBorder()
 *
 * \param[in]    pixs                   all depths; colormap ok
 * \param[in]    left, right, top, bot  number of pixels added
 * \return  pixd, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) This applies what is effectively mirror boundary conditions.
 *          For the added border pixels in pixd, the pixels in pixs
 *          near the border are mirror-copied into the border region.
 *      (2) This is useful for avoiding special operations near
 *          boundaries when doing image processing operations
 *          such as rank filters and convolution.  In use, one first
 *          adds mirrored pixels to each side of the image.  The number
 *          of pixels added on each side is half the filter dimension.
 *          Then the image processing operations proceed over a
 *          region equal to the size of the original image, and
 *          write directly into a dest pix of the same size as pixs.
 *      (3) The general pixRasterop() is used for an in-place operation here
 *          because there is no overlap between the src and dest rectangles.
 * </pre>
 */
PIX  *
pixAddMirroredBorder(PIX      *pixs,
                      l_int32  left,
                      l_int32  right,
                      l_int32  top,
                      l_int32  bot)
{
l_int32  i, j, w, h;
PIX     *pixd;

    PROCNAME("pixAddMirroredBorder");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
    pixGetDimensions(pixs, &w, &h, NULL);
    if (left > w || right > w || top > h || bot > h)
        return (PIX *)ERROR_PTR("border too large", procName, NULL);

        /* Set pixels on left, right, top and bottom, in that order */
    pixd = pixAddBorderGeneral(pixs, left, right, top, bot, 0);
    for (j = 0; j < left; j++)
        pixRasterop(pixd, left - 1 - j, top, 1, h, PIX_SRC,
                    pixd, left + j, top);
    for (j = 0; j < right; j++)
        pixRasterop(pixd, left + w + j, top, 1, h, PIX_SRC,
                    pixd, left + w - 1 - j, top);
    for (i = 0; i < top; i++)
        pixRasterop(pixd, 0, top - 1 - i, left + w + right, 1, PIX_SRC,
                    pixd, 0, top + i);
    for (i = 0; i < bot; i++)
        pixRasterop(pixd, 0, top + h + i, left + w + right, 1, PIX_SRC,
                    pixd, 0, top + h - 1 - i);

    return pixd;
}


/*!
 * \brief   pixAddRepeatedBorder()
 *
 * \param[in]    pixs                   all depths; colormap ok
 * \param[in]    left, right, top, bot  number of pixels added
 * \return  pixd, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) This applies a repeated border, as if the central part of
 *          the image is tiled over the plane.  So, for example, the
 *          pixels in the left border come from the right side of the image.
 *      (2) The general pixRasterop() is used for an in-place operation here
 *          because there is no overlap between the src and dest rectangles.
 * </pre>
 */
PIX  *
pixAddRepeatedBorder(PIX      *pixs,
                     l_int32  left,
                     l_int32  right,
                     l_int32  top,
                     l_int32  bot)
{
l_int32  w, h;
PIX     *pixd;

    PROCNAME("pixAddRepeatedBorder");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
    pixGetDimensions(pixs, &w, &h, NULL);
    if (left > w || right > w || top > h || bot > h)
        return (PIX *)ERROR_PTR("border too large", procName, NULL);

    pixd = pixAddBorderGeneral(pixs, left, right, top, bot, 0);

        /* Set pixels on left, right, top and bottom, in that order */
    pixRasterop(pixd, 0, top, left, h, PIX_SRC, pixd, w, top);
    pixRasterop(pixd, left + w, top, right, h, PIX_SRC, pixd, left, top);
    pixRasterop(pixd, 0, 0, left + w + right, top, PIX_SRC, pixd, 0, h);
    pixRasterop(pixd, 0, top + h, left + w + right, bot, PIX_SRC, pixd, 0, top);

    return pixd;
}


/*!
 * \brief   pixAddMixedBorder()
 *
 * \param[in]    pixs                   all depths; colormap ok
 * \param[in]    left, right, top, bot  number of pixels added
 * \return  pixd, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) This applies mirrored boundary conditions horizontally
 *          and repeated b.c. vertically.
 *      (2) It is specifically used for avoiding special operations
 *          near boundaries when convolving a hue-saturation histogram
 *          with a given window size.  The repeated b.c. are used
 *          vertically for hue, and the mirrored b.c. are used
 *          horizontally for saturation.  The number of pixels added
 *          on each side is approximately (but not quite) half the
 *          filter dimension.  The image processing operations can
 *          then proceed over a region equal to the size of the original
 *          image, and write directly into a dest pix of the same
 *          size as pixs.
 *      (3) The general pixRasterop() can be used for an in-place
 *          operation here because there is no overlap between the
 *          src and dest rectangles.
 * </pre>
 */
PIX  *
pixAddMixedBorder(PIX      *pixs,
                  l_int32  left,
                  l_int32  right,
                  l_int32  top,
                  l_int32  bot)
{
l_int32  j, w, h;
PIX     *pixd;

    PROCNAME("pixAddMixedBorder");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
    pixGetDimensions(pixs, &w, &h, NULL);
    if (left > w || right > w || top > h || bot > h)
        return (PIX *)ERROR_PTR("border too large", procName, NULL);

        /* Set mirrored pixels on left and right;
         * then set repeated pixels on top and bottom. */
    pixd = pixAddBorderGeneral(pixs, left, right, top, bot, 0);
    for (j = 0; j < left; j++)
        pixRasterop(pixd, left - 1 - j, top, 1, h, PIX_SRC,
                    pixd, left + j, top);
    for (j = 0; j < right; j++)
        pixRasterop(pixd, left + w + j, top, 1, h, PIX_SRC,
                    pixd, left + w - 1 - j, top);
    pixRasterop(pixd, 0, 0, left + w + right, top, PIX_SRC, pixd, 0, h);
    pixRasterop(pixd, 0, top + h, left + w + right, bot, PIX_SRC, pixd, 0, top);

    return pixd;
}


/*!
 * \brief   pixAddContinuedBorder()
 *
 * \param[in]    pixs                   all depths; colormap ok
 * \param[in]    left, right, top, bot  pixels on each side to be added
 * \return  pixd, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) This adds pixels on each side whose values are equal to
 *          the value on the closest boundary pixel.
 * </pre>
 */
PIX *
pixAddContinuedBorder(PIX     *pixs,
                      l_int32  left,
                      l_int32  right,
                      l_int32  top,
                      l_int32  bot)
{
l_int32  i, j, w, h;
PIX     *pixd;

    PROCNAME("pixAddContinuedBorder");

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

    pixd = pixAddBorderGeneral(pixs, left, right, top, bot, 0);
    pixGetDimensions(pixs, &w, &h, NULL);
    for (j = 0; j < left; j++)
        pixRasterop(pixd, j, top, 1, h, PIX_SRC, pixd, left, top);
    for (j = 0; j < right; j++)
        pixRasterop(pixd, left + w + j, top, 1, h,
                    PIX_SRC, pixd, left + w - 1, top);
    for (i = 0; i < top; i++)
        pixRasterop(pixd, 0, i, left + w + right, 1, PIX_SRC, pixd, 0, top);
    for (i = 0; i < bot; i++)
        pixRasterop(pixd, 0, top + h + i, left + w + right, 1,
                    PIX_SRC, pixd, 0, top + h - 1);

    return pixd;
}


/*-------------------------------------------------------------------*
 *                     Helper functions using alpha                  *
 *-------------------------------------------------------------------*/
/*!
 * \brief   pixShiftAndTransferAlpha()
 *
 * \param[in]    pixd            32 bpp
 * \param[in]    pixs            32 bpp
 * \param[in]    shiftx, shifty
 * \return  0 if OK; 1 on error
 */
l_ok
pixShiftAndTransferAlpha(PIX       *pixd,
                         PIX       *pixs,
                         l_float32  shiftx,
                         l_float32  shifty)
{
l_int32  w, h;
PIX     *pix1, *pix2;

    PROCNAME("pixShiftAndTransferAlpha");

    if (!pixs || !pixd)
        return ERROR_INT("pixs and pixd not both defined", procName, 1);
    if (pixGetDepth(pixs) != 32 || pixGetSpp(pixs) != 4)
        return ERROR_INT("pixs not 32 bpp and 4 spp", procName, 1);
    if (pixGetDepth(pixd) != 32)
        return ERROR_INT("pixd not 32 bpp", procName, 1);

    if (shiftx == 0 && shifty == 0) {
        pixCopyRGBComponent(pixd, pixs, L_ALPHA_CHANNEL);
        return 0;
    }

    pix1 = pixGetRGBComponent(pixs, L_ALPHA_CHANNEL);
    pixGetDimensions(pixd, &w, &h, NULL);
    pix2 = pixCreate(w, h, 8);
    pixRasterop(pix2, 0, 0, w, h, PIX_SRC, pix1, -shiftx, -shifty);
    pixSetRGBComponent(pixd, pix2, L_ALPHA_CHANNEL);
    pixDestroy(&pix1);
    pixDestroy(&pix2);
    return 0;
}


/*!
 * \brief   pixDisplayLayersRGBA()
 *
 * \param[in]    pixs   cmap or 32 bpp rgba
 * \param[in]    val    32 bit unsigned color to use as background
 * \param[in]    maxw   max output image width; 0 for no scaling
 * \return  pixd showing various image views, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) Use %val == 0xffffff00 for white background.
 *      (2) Three views are given:
 *           ~ the image with a fully opaque alpha
 *           ~ the alpha layer
 *           ~ the image as it would appear with a white background.
 * </pre>
 */
PIX *
pixDisplayLayersRGBA(PIX      *pixs,
                     l_uint32  val,
                     l_int32   maxw)
{
l_int32    w, width;
l_float32  scalefact;
PIX       *pix1, *pix2, *pixd;
PIXA      *pixa;
PIXCMAP   *cmap;

    PROCNAME("pixDisplayLayersRGBA");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
    cmap = pixGetColormap(pixs);
    if (!cmap && !(pixGetDepth(pixs) == 32 && pixGetSpp(pixs) == 4))
        return (PIX *)ERROR_PTR("pixs not cmap and not 32 bpp rgba",
                                procName, NULL);
    if ((w = pixGetWidth(pixs)) == 0)
        return (PIX *)ERROR_PTR("pixs width 0 !!", procName, NULL);

    if (cmap)
        pix1 = pixRemoveColormap(pixs, REMOVE_CMAP_WITH_ALPHA);
    else
        pix1 = pixCopy(NULL, pixs);

        /* Scale if necessary so the output width is not larger than maxw */
    scalefact = (maxw == 0) ? 1.0 : L_MIN(1.0, (l_float32)(maxw) / w);
    width = (l_int32)(scalefact * w);

    pixa = pixaCreate(3);
    pixSetSpp(pix1, 3);
    pixaAddPix(pixa, pix1, L_INSERT);  /* show the rgb values */
    pix1 = pixGetRGBComponent(pixs, L_ALPHA_CHANNEL);
    pix2 = pixConvertTo32(pix1);
    pixaAddPix(pixa, pix2, L_INSERT);  /* show the alpha channel */
    pixDestroy(&pix1);
    pix1 = pixAlphaBlendUniform(pixs, (val & 0xffffff00));
    pixaAddPix(pixa, pix1, L_INSERT);  /* with %val color bg showing */
    pixd = pixaDisplayTiledInRows(pixa, 32, width, scalefact, 0, 25, 2);
    pixaDestroy(&pixa);
    return pixd;
}


/*-------------------------------------------------------------*
 *                Color sample setting and extraction          *
 *-------------------------------------------------------------*/
/*!
 * \brief   pixCreateRGBImage()
 *
 * \param[in]   pixr   8 bpp red pix
 * \param[in]   pixg   8 bpp green pix
 * \param[in]   pixb   8 bpp blue pix
 * \return  32 bpp pix, interleaved with 4 samples/pixel,
 *              or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) the 4th byte, sometimes called the "alpha channel",
 *          and which is often used for blending between different
 *          images, is left with 0 value.
 *      (2) see Note (4) in pix.h for details on storage of
 *          8-bit samples within each 32-bit word.
 *      (3) This implementation, setting the r, g and b components
 *          sequentially, is much faster than setting them in parallel
 *          by constructing an RGB dest pixel and writing it to dest.
 *          The reason is there are many more cache misses when reading
 *          from 3 input images simultaneously.
 * </pre>
 */
PIX *
pixCreateRGBImage(PIX  *pixr,
                  PIX  *pixg,
                  PIX  *pixb)
{
l_int32  wr, wg, wb, hr, hg, hb, dr, dg, db;
PIX     *pixd;

    PROCNAME("pixCreateRGBImage");

    if (!pixr)
        return (PIX *)ERROR_PTR("pixr not defined", procName, NULL);
    if (!pixg)
        return (PIX *)ERROR_PTR("pixg not defined", procName, NULL);
    if (!pixb)
        return (PIX *)ERROR_PTR("pixb not defined", procName, NULL);
    pixGetDimensions(pixr, &wr, &hr, &dr);
    pixGetDimensions(pixg, &wg, &hg, &dg);
    pixGetDimensions(pixb, &wb, &hb, &db);
    if (dr != 8 || dg != 8 || db != 8)
        return (PIX *)ERROR_PTR("input pix not all 8 bpp", procName, NULL);
    if (wr != wg || wr != wb)
        return (PIX *)ERROR_PTR("widths not the same", procName, NULL);
    if (hr != hg || hr != hb)
        return (PIX *)ERROR_PTR("heights not the same", procName, NULL);

    if ((pixd = pixCreate(wr, hr, 32)) == NULL)
        return (PIX *)ERROR_PTR("pixd not made", procName, NULL);
    pixCopyResolution(pixd, pixr);
    pixSetRGBComponent(pixd, pixr, COLOR_RED);
    pixSetRGBComponent(pixd, pixg, COLOR_GREEN);
    pixSetRGBComponent(pixd, pixb, COLOR_BLUE);

    return pixd;
}


/*!
 * \brief   pixGetRGBComponent()
 *
 * \param[in]   pixs   32 bpp, or colormapped
 * \param[in]   comp   one of {COLOR_RED, COLOR_GREEN, COLOR_BLUE,
 *                     L_ALPHA_CHANNEL}
 * \return  pixd the selected 8 bpp component image of the
 *                    input 32 bpp image or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) Three calls to this function generate the r, g and b 8 bpp
 *          component images.  This is much faster than generating the
 *          three images in parallel, by extracting a src pixel and setting
 *          the pixels of each component image from it.  The reason is
 *          there are many more cache misses when writing to three
 *          output images simultaneously.
 * </pre>
 */
PIX *
pixGetRGBComponent(PIX     *pixs,
                   l_int32  comp)
{
l_int32    i, j, w, h, wpls, wpld, val;
l_uint32  *lines, *lined;
l_uint32  *datas, *datad;
PIX       *pixd;

    PROCNAME("pixGetRGBComponent");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
    if (pixGetColormap(pixs))
        return pixGetRGBComponentCmap(pixs, comp);
    if (pixGetDepth(pixs) != 32)
        return (PIX *)ERROR_PTR("pixs not 32 bpp", procName, NULL);
    if (comp != COLOR_RED && comp != COLOR_GREEN &&
        comp != COLOR_BLUE && comp != L_ALPHA_CHANNEL)
        return (PIX *)ERROR_PTR("invalid comp", procName, NULL);

    pixGetDimensions(pixs, &w, &h, NULL);
    if ((pixd = pixCreate(w, h, 8)) == NULL)
        return (PIX *)ERROR_PTR("pixd not made", procName, NULL);
    pixCopyResolution(pixd, pixs);
    wpls = pixGetWpl(pixs);
    wpld = pixGetWpl(pixd);
    datas = pixGetData(pixs);
    datad = pixGetData(pixd);
    for (i = 0; i < h; i++) {
        lines = datas + i * wpls;
        lined = datad + i * wpld;
        for (j = 0; j < w; j++) {
            val = GET_DATA_BYTE(lines + j, comp);
            SET_DATA_BYTE(lined, j, val);
        }
    }

    return pixd;
}


/*!
 * \brief   pixSetRGBComponent()
 *
 * \param[in]   pixd   32 bpp
 * \param[in]   pixs   8 bpp
 * \param[in]   comp   one of the set: {COLOR_RED, COLOR_GREEN,
 *                                      COLOR_BLUE, L_ALPHA_CHANNEL}
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This places the 8 bpp pixel in pixs into the
 *          specified component (properly interleaved) in pixd,
 *      (2) The two images are registered to the UL corner; the sizes
 *          need not be the same, but a warning is issued if they differ.
 * </pre>
 */
l_ok
pixSetRGBComponent(PIX     *pixd,
                   PIX     *pixs,
                   l_int32  comp)
{
l_uint8    srcbyte;
l_int32    i, j, w, h, ws, hs, wd, hd;
l_int32    wpls, wpld;
l_uint32  *lines, *lined;
l_uint32  *datas, *datad;

    PROCNAME("pixSetRGBComponent");

    if (!pixd)
        return ERROR_INT("pixd not defined", procName, 1);
    if (!pixs)
        return ERROR_INT("pixs not defined", procName, 1);
    if (pixGetDepth(pixd) != 32)
        return ERROR_INT("pixd not 32 bpp", procName, 1);
    if (pixGetDepth(pixs) != 8)
        return ERROR_INT("pixs not 8 bpp", procName, 1);
    if (comp != COLOR_RED && comp != COLOR_GREEN &&
        comp != COLOR_BLUE && comp != L_ALPHA_CHANNEL)
        return ERROR_INT("invalid comp", procName, 1);
    pixGetDimensions(pixs, &ws, &hs, NULL);
    pixGetDimensions(pixd, &wd, &hd, NULL);
    if (ws != wd || hs != hd)
        L_WARNING("images sizes not equal\n", procName);
    w = L_MIN(ws, wd);
    h = L_MIN(hs, hd);
    if (comp == L_ALPHA_CHANNEL)
        pixSetSpp(pixd, 4);
    datas = pixGetData(pixs);
    datad = pixGetData(pixd);
    wpls = pixGetWpl(pixs);
    wpld = pixGetWpl(pixd);
    for (i = 0; i < h; i++) {
        lines = datas + i * wpls;
        lined = datad + i * wpld;
        for (j = 0; j < w; j++) {
            srcbyte = GET_DATA_BYTE(lines, j);
            SET_DATA_BYTE(lined + j, comp, srcbyte);
        }
    }

    return 0;
}


/*!
 * \brief   pixGetRGBComponentCmap()
 *
 * \param[in]   pixs   colormapped
 * \param[in]   comp   one of the set: {COLOR_RED, COLOR_GREEN, COLOR_BLUE}
 * \return  pixd  the selected 8 bpp component image of the
 *                     input cmapped image, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) In leptonica, we do not support alpha in colormaps.
 * </pre>
 */
PIX *
pixGetRGBComponentCmap(PIX     *pixs,
                       l_int32  comp)
{
l_int32     i, j, w, h, val, index, valid;
l_int32     wplc, wpld;
l_uint32   *linec, *lined;
l_uint32   *datac, *datad;
PIX        *pixc, *pixd;
PIXCMAP    *cmap;
RGBA_QUAD  *cta;

    PROCNAME("pixGetRGBComponentCmap");

    if (!pixs)
        return (PIX *)ERROR_PTR("pixs not defined", procName, NULL);
    if ((cmap = pixGetColormap(pixs)) == NULL)
        return (PIX *)ERROR_PTR("pixs not cmapped", procName, NULL);
    if (comp == L_ALPHA_CHANNEL)
        return (PIX *)ERROR_PTR("alpha in cmaps not supported", procName, NULL);
    if (comp != COLOR_RED && comp != COLOR_GREEN && comp != COLOR_BLUE)
        return (PIX *)ERROR_PTR("invalid comp", procName, NULL);

        /* If not 8 bpp, make a cmapped 8 bpp pix */
    if (pixGetDepth(pixs) == 8)
        pixc = pixClone(pixs);
    else
        pixc = pixConvertTo8(pixs, TRUE);
    pixcmapIsValid(cmap, pixc, &valid);
    if (!valid) {
        pixDestroy(&pixc);
        return (PIX *)ERROR_PTR("invalid colormap", procName, NULL);
    }

    pixGetDimensions(pixs, &w, &h, NULL);
    if ((pixd = pixCreateNoInit(w, h, 8)) == NULL) {
        pixDestroy(&pixc);
        return (PIX *)ERROR_PTR("pixd not made", procName, NULL);
    }
    pixCopyResolution(pixd, pixs);
    wplc = pixGetWpl(pixc);
    wpld = pixGetWpl(pixd);
    datac = pixGetData(pixc);
    datad = pixGetData(pixd);
    cta = (RGBA_QUAD *)cmap->array;

    for (i = 0; i < h; i++) {
        linec = datac + i * wplc;
        lined = datad + i * wpld;
        if (comp == COLOR_RED) {
            for (j = 0; j < w; j++) {
                index = GET_DATA_BYTE(linec, j);
                val = cta[index].red;
                SET_DATA_BYTE(lined, j, val);
            }
        } else if (comp == COLOR_GREEN) {
            for (j = 0; j < w; j++) {
                index = GET_DATA_BYTE(linec, j);
                val = cta[index].green;
                SET_DATA_BYTE(lined, j, val);
            }
        } else if (comp == COLOR_BLUE) {
            for (j = 0; j < w; j++) {
                index = GET_DATA_BYTE(linec, j);
                val = cta[index].blue;
                SET_DATA_BYTE(lined, j, val);
            }
        }
    }

    pixDestroy(&pixc);
    return pixd;
}


/*!
 * \brief   pixCopyRGBComponent()
 *
 * \param[in]   pixd   32 bpp
 * \param[in]   pixs   32 bpp
 * \param[in]   comp   one of the set: {COLOR_RED, COLOR_GREEN,
 *                                      COLOR_BLUE, L_ALPHA_CHANNEL}
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) The two images are registered to the UL corner.  The sizes
 *          are usually the same, and a warning is issued if they differ.
 * </pre>
 */
l_ok
pixCopyRGBComponent(PIX     *pixd,
                    PIX     *pixs,
                    l_int32  comp)
{
l_int32    i, j, w, h, ws, hs, wd, hd, val;
l_int32    wpls, wpld;
l_uint32  *lines, *lined;
l_uint32  *datas, *datad;

    PROCNAME("pixCopyRGBComponent");

    if (!pixd && pixGetDepth(pixd) != 32)
        return ERROR_INT("pixd not defined or not 32 bpp", procName, 1);
    if (!pixs && pixGetDepth(pixs) != 32)
        return ERROR_INT("pixs not defined or not 32 bpp", procName, 1);
    if (comp != COLOR_RED && comp != COLOR_GREEN &&
        comp != COLOR_BLUE && comp != L_ALPHA_CHANNEL)
        return ERROR_INT("invalid component", procName, 1);
    pixGetDimensions(pixs, &ws, &hs, NULL);
    pixGetDimensions(pixd, &wd, &hd, NULL);
    if (ws != wd || hs != hd)
        L_WARNING("images sizes not equal\n", procName);
    w = L_MIN(ws, wd);
    h = L_MIN(hs, hd);
    if (comp == L_ALPHA_CHANNEL)
        pixSetSpp(pixd, 4);
    wpls = pixGetWpl(pixs);
    wpld = pixGetWpl(pixd);
    datas = pixGetData(pixs);
    datad = pixGetData(pixd);
    for (i = 0; i < h; i++) {
        lines = datas + i * wpls;
        lined = datad + i * wpld;
        for (j = 0; j < w; j++) {
            val = GET_DATA_BYTE(lines + j, comp);
            SET_DATA_BYTE(lined + j, comp, val);
        }
    }
    return 0;
}


/*!
 * \brief   composeRGBPixel()
 *
 * \param[in]    rval, gval, bval
 * \param[out]   ppixel             32-bit pixel
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) All channels are 8 bits: the input values must be between
 *          0 and 255.  For speed, this is not enforced by masking
 *          with 0xff before shifting.
 *      (2) A slower implementation uses macros:
 *            SET_DATA_BYTE(ppixel, COLOR_RED, rval);
 *            SET_DATA_BYTE(ppixel, COLOR_GREEN, gval);
 *            SET_DATA_BYTE(ppixel, COLOR_BLUE, bval);
 * </pre>
 */
l_ok
composeRGBPixel(l_int32    rval,
                l_int32    gval,
                l_int32    bval,
                l_uint32  *ppixel)
{
    PROCNAME("composeRGBPixel");

    if (!ppixel)
        return ERROR_INT("&pixel not defined", procName, 1);

    *ppixel = ((l_uint32)rval << L_RED_SHIFT) |
              ((l_uint32)gval << L_GREEN_SHIFT) |
              ((l_uint32)bval << L_BLUE_SHIFT);
    return 0;
}


/*!
 * \brief   composeRGBAPixel()
 *
 * \param[in]    rval, gval, bval, aval
 * \param[out]   ppixel                  32-bit pixel
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) All channels are 8 bits: the input values must be between
 *          0 and 255.  For speed, this is not enforced by masking
 *          with 0xff before shifting.
 * </pre>
 */
l_ok
composeRGBAPixel(l_int32    rval,
                 l_int32    gval,
                 l_int32    bval,
                 l_int32    aval,
                 l_uint32  *ppixel)
{
    PROCNAME("composeRGBAPixel");

    if (!ppixel)
        return ERROR_INT("&pixel not defined", procName, 1);

    *ppixel = ((l_uint32)rval << L_RED_SHIFT) |
              ((l_uint32)gval << L_GREEN_SHIFT) |
              ((l_uint32)bval << L_BLUE_SHIFT) |
              aval;
    return 0;
}


/*!
 * \brief   extractRGBValues()
 *
 * \param[in]    pixel   32 bit
 * \param[out]   prval   [optional] red component
 * \param[out]   pgval   [optional] green component
 * \param[out]   pbval   [optional] blue component
 * \return  void
 *
 * <pre>
 * Notes:
 *      (1) A slower implementation uses macros:
 *             *prval = GET_DATA_BYTE(&pixel, COLOR_RED);
 *             *pgval = GET_DATA_BYTE(&pixel, COLOR_GREEN);
 *             *pbval = GET_DATA_BYTE(&pixel, COLOR_BLUE);
 * </pre>
 */
void
extractRGBValues(l_uint32  pixel,
                 l_int32  *prval,
                 l_int32  *pgval,
                 l_int32  *pbval)
{
    if (prval) *prval = (pixel >> L_RED_SHIFT) & 0xff;
    if (pgval) *pgval = (pixel >> L_GREEN_SHIFT) & 0xff;
    if (pbval) *pbval = (pixel >> L_BLUE_SHIFT) & 0xff;
}


/*!
 * \brief   extractRGBAValues()
 *
 * \param[in]    pixel   32 bit
 * \param[out]   prval   [optional] red component
 * \param[out]   pgval   [optional] green component
 * \param[out]   pbval   [optional] blue component
 * \param[out]   paval   [optional] alpha component
 * \return  void
 */
void
extractRGBAValues(l_uint32  pixel,
                  l_int32  *prval,
                  l_int32  *pgval,
                  l_int32  *pbval,
                  l_int32  *paval)
{
    if (prval) *prval = (pixel >> L_RED_SHIFT) & 0xff;
    if (pgval) *pgval = (pixel >> L_GREEN_SHIFT) & 0xff;
    if (pbval) *pbval = (pixel >> L_BLUE_SHIFT) & 0xff;
    if (paval) *paval = (pixel >> L_ALPHA_SHIFT) & 0xff;
}


/*!
 * \brief   extractMinMaxComponent()
 *
 * \param[in]   pixel   32 bpp RGB
 * \param[in]   type    L_CHOOSE_MIN or L_CHOOSE_MAX
 * \return  component in range [0 ... 255], or NULL on error
 */
l_int32
extractMinMaxComponent(l_uint32  pixel,
                       l_int32   type)
{
l_int32  rval, gval, bval, val;

    extractRGBValues(pixel, &rval, &gval, &bval);
    if (type == L_CHOOSE_MIN) {
        val = L_MIN(rval, gval);
        val = L_MIN(val, bval);
    } else {  /* type == L_CHOOSE_MAX */
        val = L_MAX(rval, gval);
        val = L_MAX(val, bval);
    }
    return val;
}


/*!
 * \brief   pixGetRGBLine()
 *
 * \param[in]   pixs   32 bpp
 * \param[in]   row
 * \param[in]   bufr   array of red samples; size w bytes
 * \param[in]   bufg   array of green samples; size w bytes
 * \param[in]   bufb   array of blue samples; size w bytes
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This puts rgb components from the input line in pixs
 *          into the given buffers.
 * </pre>
 */
l_ok
pixGetRGBLine(PIX      *pixs,
              l_int32   row,
              l_uint8  *bufr,
              l_uint8  *bufg,
              l_uint8  *bufb)
{
l_uint32  *lines;
l_int32    j, w, h;
l_int32    wpls;

    PROCNAME("pixGetRGBLine");

    if (!pixs)
        return ERROR_INT("pixs not defined", procName, 1);
    if (pixGetDepth(pixs) != 32)
        return ERROR_INT("pixs not 32 bpp", procName, 1);
    if (!bufr || !bufg || !bufb)
        return ERROR_INT("buffer not defined", procName, 1);

    pixGetDimensions(pixs, &w, &h, NULL);
    if (row < 0 || row >= h)
        return ERROR_INT("row out of bounds", procName, 1);
    wpls = pixGetWpl(pixs);
    lines = pixGetData(pixs) + row * wpls;

    for (j = 0; j < w; j++) {
        bufr[j] = GET_DATA_BYTE(lines + j, COLOR_RED);
        bufg[j] = GET_DATA_BYTE(lines + j, COLOR_GREEN);
        bufb[j] = GET_DATA_BYTE(lines + j, COLOR_BLUE);
    }

    return 0;
}


/*-------------------------------------------------------------*
 *                   Raster line pixel setter                  *
 *-------------------------------------------------------------*/
/*!
 * \brief   setLineDataVal()
 *
 * \param[in]    line    ptr to first word in raster line data
 * \param[in]    j       index of pixels into the raster line
 * \param[in]    d       depth of the pixel
 * \param[in]    val     pixel value to be set
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This is a convenience function to set a pixel value in a
 *          raster line where the depth of the image can have different
 *          values (1, 2, 4, 8, 16 or 32).
 * </pre>
 */
l_ok
setLineDataVal(l_uint32  *line,
               l_int32    j,
               l_int32    d,
               l_uint32   val)
{
    PROCNAME("setLineDataVal");

    if (!line)
        return ERROR_INT("line not defined", procName, 1);
    if (j < 0)
        return ERROR_INT("j must be >= 0", procName, 1);
    if (d != 1 && d != 2 && d != 4 && d != 8 && d != 16 && d != 32)
        return ERROR_INT("invalid d", procName, 1);

    if (d == 1)
        SET_DATA_BIT_VAL(line, j, val);
    else if (d == 2)
        SET_DATA_DIBIT(line, j, val);
    else if (d == 4)
        SET_DATA_QBIT(line, j, val);
    else if (d == 8)
        SET_DATA_BYTE(line, j, val);
    else if (d == 16)
        SET_DATA_TWO_BYTES(line, j, val);
    else  /* d == 32 */
        *(line + j) = val;
    return 0;
}


/*-------------------------------------------------------------*
 *                    Pixel endian conversion                  *
 *-------------------------------------------------------------*/
/*!
 * \brief   pixEndianByteSwapNew()
 *
 * \param[in]    pixs
 * \return  pixd, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) This is used to convert the data in a pix to a
 *          serialized byte buffer in raster order, and, for RGB,
 *          in order RGBA.  This requires flipping bytes within
 *          each 32-bit word for little-endian platforms, because the
 *          words have a MSB-to-the-left rule, whereas byte raster-order
 *          requires the left-most byte in each word to be byte 0.
 *          For big-endians, no swap is necessary, so this returns a clone.
 *      (2) Unlike pixEndianByteSwap(), which swaps the bytes in-place,
 *          this returns a new pix (or a clone).  We provide this
 *          because often when serialization is done, the source
 *          pix needs to be restored to canonical little-endian order,
 *          and this requires a second byte swap.  In such a situation,
 *          it is twice as fast to make a new pix in big-endian order,
 *          use it, and destroy it.
 * </pre>
 */
PIX *
pixEndianByteSwapNew(PIX  *pixs)
{
l_uint32  *datas, *datad;
l_int32    i, j, h, wpl;
l_uint32   word;
PIX       *pixd;

    PROCNAME("pixEndianByteSwapNew");

#ifdef L_BIG_ENDIAN

    return pixClone(pixs);

#else   /* L_LITTLE_ENDIAN */

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

    datas = pixGetData(pixs);
    wpl = pixGetWpl(pixs);
    h = pixGetHeight(pixs);
    if ((pixd = pixCreateTemplate(pixs)) == NULL)
        return (PIX *)ERROR_PTR("pixd not made", procName, NULL);
    datad = pixGetData(pixd);
    for (i = 0; i < h; i++) {
        for (j = 0; j < wpl; j++, datas++, datad++) {
            word = *datas;
            *datad = (word >> 24) |
                    ((word >> 8) & 0x0000ff00) |
                    ((word << 8) & 0x00ff0000) |
                    (word << 24);
        }
    }

    return pixd;

#endif   /* L_BIG_ENDIAN */

}


/*!
 * \brief   pixEndianByteSwap()
 *
 * \param[in]   pixs
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This is used on little-endian platforms to swap
 *          the bytes within a word; bytes 0 and 3 are swapped,
 *          and bytes 1 and 2 are swapped.
 *      (2) This is required for little-endians in situations
 *          where we convert from a serialized byte order that is
 *          in raster order, as one typically has in file formats,
 *          to one with MSB-to-the-left in each 32-bit word, or v.v.
 *          See pix.h for a description of the canonical format
 *          (MSB-to-the left) that is used for both little-endian
 *          and big-endian platforms.   For big-endians, the
 *          MSB-to-the-left word order has the bytes in raster
 *          order when serialized, so no byte flipping is required.
 * </pre>
 */
l_ok
pixEndianByteSwap(PIX  *pixs)
{
l_uint32  *data;
l_int32    i, j, h, wpl;
l_uint32   word;

    PROCNAME("pixEndianByteSwap");

#ifdef L_BIG_ENDIAN

    return 0;

#else   /* L_LITTLE_ENDIAN */

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

    data = pixGetData(pixs);
    wpl = pixGetWpl(pixs);
    h = pixGetHeight(pixs);
    for (i = 0; i < h; i++) {
        for (j = 0; j < wpl; j++, data++) {
            word = *data;
            *data = (word >> 24) |
                    ((word >> 8) & 0x0000ff00) |
                    ((word << 8) & 0x00ff0000) |
                    (word << 24);
        }
    }

    return 0;

#endif   /* L_BIG_ENDIAN */

}


/*!
 * \brief   lineEndianByteSwap()
 *
 * \param[in]  datad   dest byte array data, reordered on little-endians
 * \param[in]  datas   a src line of pix data)
 * \param[in]  wpl     number of 32 bit words in the line
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This is used on little-endian platforms to swap
 *          the bytes within each word in the line of image data.
 *          Bytes 0 <==> 3 and 1 <==> 2 are swapped in the dest
 *          byte array data8d, relative to the pix data in datas.
 *      (2) The bytes represent 8 bit pixel values.  They are swapped
 *          for little endians so that when the dest array datad
 *          is addressed by bytes, the pixels are chosen sequentially
 *          from left to right in the image.
 * </pre>
 */
l_int32
lineEndianByteSwap(l_uint32  *datad,
                   l_uint32  *datas,
                   l_int32    wpl)
{
l_int32   j;
l_uint32  word;

    PROCNAME("lineEndianByteSwap");

    if (!datad || !datas)
        return ERROR_INT("datad and datas not both defined", procName, 1);

#ifdef L_BIG_ENDIAN

    memcpy(datad, datas, 4 * wpl);
    return 0;

#else   /* L_LITTLE_ENDIAN */

    for (j = 0; j < wpl; j++, datas++, datad++) {
        word = *datas;
        *datad = (word >> 24) |
                 ((word >> 8) & 0x0000ff00) |
                 ((word << 8) & 0x00ff0000) |
                 (word << 24);
    }
    return 0;

#endif   /* L_BIG_ENDIAN */

}


/*!
 * \brief   pixEndianTwoByteSwapNew()
 *
 * \param[in]    pixs
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This is used on little-endian platforms to swap the
 *          2-byte entities within a 32-bit word.
 *      (2) This is equivalent to a full byte swap, as performed
 *          by pixEndianByteSwap(), followed by byte swaps in
 *          each of the 16-bit entities separately.
 *      (3) Unlike pixEndianTwoByteSwap(), which swaps the shorts in-place,
 *          this returns a new pix (or a clone).  We provide this
 *          to avoid having to swap twice in situations where the input
 *          pix must be restored to canonical little-endian order.
 * </pre>
 */
PIX *
pixEndianTwoByteSwapNew(PIX  *pixs)
{
l_uint32  *datas, *datad;
l_int32    i, j, h, wpl;
l_uint32   word;
PIX       *pixd;

    PROCNAME("pixEndianTwoByteSwapNew");

#ifdef L_BIG_ENDIAN

    return pixClone(pixs);

#else   /* L_LITTLE_ENDIAN */

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

    datas = pixGetData(pixs);
    wpl = pixGetWpl(pixs);
    h = pixGetHeight(pixs);
    if ((pixd = pixCreateTemplate(pixs)) == NULL)
        return (PIX *)ERROR_PTR("pixd not made", procName, NULL);
    datad = pixGetData(pixd);
    for (i = 0; i < h; i++) {
        for (j = 0; j < wpl; j++, datas++, datad++) {
            word = *datas;
            *datad = (word << 16) | (word >> 16);
        }
    }

    return pixd;

#endif   /* L_BIG_ENDIAN */

}


/*!
 * \brief   pixEndianTwoByteSwap()
 *
 * \param[in]    pixs
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This is used on little-endian platforms to swap the
 *          2-byte entities within a 32-bit word.
 *      (2) This is equivalent to a full byte swap, as performed
 *          by pixEndianByteSwap(), followed by byte swaps in
 *          each of the 16-bit entities separately.
 * </pre>
 */
l_ok
pixEndianTwoByteSwap(PIX  *pixs)
{
l_uint32  *data;
l_int32    i, j, h, wpl;
l_uint32   word;

    PROCNAME("pixEndianTwoByteSwap");

#ifdef L_BIG_ENDIAN

    return 0;

#else   /* L_LITTLE_ENDIAN */

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

    data = pixGetData(pixs);
    wpl = pixGetWpl(pixs);
    h = pixGetHeight(pixs);
    for (i = 0; i < h; i++) {
        for (j = 0; j < wpl; j++, data++) {
            word = *data;
            *data = (word << 16) | (word >> 16);
        }
    }

    return 0;

#endif   /* L_BIG_ENDIAN */

}


/*-------------------------------------------------------------*
 *             Extract raster data as binary string            *
 *-------------------------------------------------------------*/
/*!
 * \brief   pixGetRasterData()
 *
 * \param[in]    pixs     1, 8, 32 bpp
 * \param[out]   pdata    raster data in memory
 * \param[out]   pnbytes  number of bytes in data string
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This returns the raster data as a byte string, padded to the
 *          byte.  For 1 bpp, the first pixel is the MSbit in the first byte.
 *          For rgb, the bytes are in (rgb) order.  This is the format
 *          required for flate encoding of pixels in a PostScript file.
 * </pre>
 */
l_ok
pixGetRasterData(PIX       *pixs,
                 l_uint8  **pdata,
                 size_t    *pnbytes)
{
l_int32    w, h, d, wpl, i, j, rval, gval, bval;
l_int32    databpl;  /* bytes for each raster line in returned data */
l_uint8   *line, *data;  /* packed data in returned array */
l_uint32  *rline, *rdata;  /* data in pix raster */

    PROCNAME("pixGetRasterData");

    if (pdata) *pdata = NULL;
    if (pnbytes) *pnbytes = 0;
    if (!pdata || !pnbytes)
        return ERROR_INT("&data and &nbytes not both defined", procName, 1);
    if (!pixs)
        return ERROR_INT("pixs not defined", procName, 1);
    pixGetDimensions(pixs, &w, &h, &d);
    if (d != 1 && d != 2 && d != 4 && d != 8 && d != 16 && d != 32)
        return ERROR_INT("depth not in {1,2,4,8,16,32}", procName, 1);
    rdata = pixGetData(pixs);
    wpl = pixGetWpl(pixs);
    if (d == 1)
        databpl = (w + 7) / 8;
    else if (d == 2)
        databpl = (w + 3) / 4;
    else if (d == 4)
        databpl = (w + 1) / 2;
    else if (d == 8 || d == 16)
        databpl = w * (d / 8);
    else  /* d == 32 bpp rgb */
        databpl = 3 * w;
    if ((data = (l_uint8 *)LEPT_CALLOC((size_t)databpl * h, sizeof(l_uint8)))
            == NULL)
        return ERROR_INT("data not allocated", procName, 1);
    *pdata = data;
    *pnbytes = (size_t)databpl * h;

    for (i = 0; i < h; i++) {
         rline = rdata + i * wpl;
         line = data + i * databpl;
         if (d <= 8) {
             for (j = 0; j < databpl; j++)
                  line[j] = GET_DATA_BYTE(rline, j);
         } else if (d == 16) {
             for (j = 0; j < w; j++)
                  line[2 * j] = GET_DATA_TWO_BYTES(rline, j);
         } else {  /* d == 32 bpp rgb */
             for (j = 0; j < w; j++) {
                  extractRGBValues(rline[j], &rval, &gval, &bval);
                  *(line + 3 * j) = rval;
                  *(line + 3 * j + 1) = gval;
                  *(line + 3 * j + 2) = bval;
             }
         }
    }

    return 0;
}


/*-------------------------------------------------------------*
 *                Infer resolution from image size             *
 *-------------------------------------------------------------*/
/*!
 * \brief   pixInferResolution()
 *
 * \param[in]    pix
 * \param[in]    longside    assumed max dimension, in inches
 * \param[out]   pres        resolution (ppi)
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This finds the resolution, assuming that the longest side
 *          of the image is %longside.  On error, returns 300 ppi.
 *      (2) This is useful for computing resolution for generating pdfs,
 *          when the images are scanned from pages of known size.
 *          There, %longside is typically about 11.0.
 * </pre>
 */
l_ok
pixInferResolution(PIX       *pix,
                   l_float32  longside,
                   l_int32   *pres)
{
l_int32  w, h, maxdim, res;

    PROCNAME("pixInferResolution");

    if (!pres)
        return ERROR_INT("&res not defined", procName, 1);
    *pres = 300;
    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);
    if (longside <= 0.0)
        return ERROR_INT("longside not > 0", procName, 1);

    pixGetDimensions(pix, &w, &h, NULL);
    maxdim = L_MAX(w, h);
    res = (l_int32)(maxdim / longside + 0.5);
    res = L_MAX(res, 1);  /* don't let it be 0 */
    if (res < 10)
        L_WARNING("low inferred resolution: %d ppi\n", procName, res);
    if (res > 10000)
        L_WARNING("high inferred resolution: %d ppi\n", procName, res);
    *pres = res;
    return 0;
}


/*-------------------------------------------------------------*
 *                 Test alpha component opaqueness             *
 *-------------------------------------------------------------*/
/*!
 * \brief   pixAlphaIsOpaque()
 *
 * \param[in]    pix       32 bpp, spp == 4
 * \param[out]   popaque   1 if spp == 4 and all alpha component
 *                         values are 255 (opaque); 0 otherwise
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      1) On error, opaque is returned as 0 (FALSE).
 * </pre>
 */
l_ok
pixAlphaIsOpaque(PIX      *pix,
                 l_int32  *popaque)
{
l_int32    w, h, wpl, i, j, alpha;
l_uint32  *data, *line;

    PROCNAME("pixAlphaIsOpaque");

    if (!popaque)
        return ERROR_INT("&opaque not defined", procName, 1);
    *popaque = FALSE;
    if (!pix)
        return ERROR_INT("&pix not defined", procName, 1);
    if (pixGetDepth(pix) != 32)
        return ERROR_INT("&pix not 32 bpp", procName, 1);
    if (pixGetSpp(pix) != 4)
        return ERROR_INT("&pix not 4 spp", procName, 1);

    data = pixGetData(pix);
    wpl = pixGetWpl(pix);
    pixGetDimensions(pix, &w, &h, NULL);
    for (i = 0; i < h; i++) {
        line = data + i * wpl;
        for (j = 0; j < w; j++) {
            alpha = GET_DATA_BYTE(line + j, L_ALPHA_CHANNEL);
            if (alpha ^ 0xff)  /* not opaque */
                return 0;
        }
    }

    *popaque = TRUE;
    return 0;
}


/*-------------------------------------------------------------*
 *             Setup helpers for 8 bpp byte processing         *
 *-------------------------------------------------------------*/
/*!
 * \brief   pixSetupByteProcessing()
 *
 * \param[in]    pix   8 bpp, no colormap
 * \param[out]   pw    [optional] width
 * \param[out]   ph    [optional] height
 * \return  line ptr array, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) This is a simple helper for processing 8 bpp images with
 *          direct byte access.  It can swap byte order within each word.
 *      (2) After processing, you must call pixCleanupByteProcessing(),
 *          which frees the lineptr array and restores byte order.
 *      (3) Usage:
 *              l_uint8 **lineptrs = pixSetupByteProcessing(pix, &w, &h);
 *              for (i = 0; i < h; i++) {
 *                  l_uint8 *line = lineptrs[i];
 *                  for (j = 0; j < w; j++) {
 *                      val = line[j];
 *                      ...
 *                  }
 *              }
 *              pixCleanupByteProcessing(pix, lineptrs);
 * </pre>
 */
l_uint8 **
pixSetupByteProcessing(PIX      *pix,
                       l_int32  *pw,
                       l_int32  *ph)
{
l_int32  w, h;

    PROCNAME("pixSetupByteProcessing");

    if (pw) *pw = 0;
    if (ph) *ph = 0;
    if (!pix || pixGetDepth(pix) != 8)
        return (l_uint8 **)ERROR_PTR("pix not defined or not 8 bpp",
                                     procName, NULL);
    pixGetDimensions(pix, &w, &h, NULL);
    if (pw) *pw = w;
    if (ph) *ph = h;
    if (pixGetColormap(pix))
        return (l_uint8 **)ERROR_PTR("pix has colormap", procName, NULL);

    pixEndianByteSwap(pix);
    return (l_uint8 **)pixGetLinePtrs(pix, NULL);
}


/*!
 * \brief   pixCleanupByteProcessing()
 *
 * \param[in]   pix        8 bpp, no colormap
 * \param[in]   lineptrs   ptrs to the beginning of each raster line of data
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This must be called after processing that was initiated
 *          by pixSetupByteProcessing() has finished.
 * </pre>
 */
l_ok
pixCleanupByteProcessing(PIX      *pix,
                         l_uint8 **lineptrs)
{
    PROCNAME("pixCleanupByteProcessing");

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

    pixEndianByteSwap(pix);
    LEPT_FREE(lineptrs);
    return 0;
}


/*------------------------------------------------------------------------*
 *      Setting parameters for antialias masking with alpha transforms    *
 *------------------------------------------------------------------------*/
/*!
 * \brief   l_setAlphaMaskBorder()
 *
 * \param[in]    val1, val2     in [0.0 ... 1.0]
 * \return  void
 *
 * <pre>
 * Notes:
 *      (1) This sets the opacity values used to generate the two outer
 *          boundary rings in the alpha mask associated with geometric
 *          transforms such as pixRotateWithAlpha().
 *      (2) The default values are val1 = 0.0 (completely transparent
 *          in the outermost ring) and val2 = 0.5 (half transparent
 *          in the second ring).  When the image is blended, this
 *          completely removes the outer ring (shrinking the image by
 *          2 in each direction), and alpha-blends with 0.5 the second ring.
 *          Using val1 = 0.25 and val2 = 0.75 gives a slightly more
 *          blurred border, with no perceptual difference at screen resolution.
 *      (3) The actual mask values are found by multiplying these
 *          normalized opacity values by 255.
 * </pre>
 */
void
l_setAlphaMaskBorder(l_float32  val1,
                     l_float32  val2)
{
    val1 = L_MAX(0.0, L_MIN(1.0, val1));
    val2 = L_MAX(0.0, L_MIN(1.0, val2));
    AlphaMaskBorderVals[0] = val1;
    AlphaMaskBorderVals[1] = val2;
}