summaryrefslogtreecommitdiff
blob: 83a5bc4810318981a9fd6027dbe09661f7643715 (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
/*====================================================================*
 -  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  boxbasic.c
 * <pre>
 *
 *   Basic 'class' functions for box, boxa and boxaa,
 *   including accessors and serialization.
 *
 *      Box creation, copy, clone, destruction
 *           BOX      *boxCreate()
 *           BOX      *boxCreateValid()
 *           BOX      *boxCopy()
 *           BOX      *boxClone()
 *           void      boxDestroy()
 *
 *      Box accessors
 *           l_int32   boxGetGeometry()
 *           l_int32   boxSetGeometry()
 *           l_int32   boxGetSideLocations()
 *           l_int32   boxSetSideLocations()
 *           l_int32   boxGetRefcount()
 *           l_int32   boxChangeRefcount()
 *           l_int32   boxIsValid()
 *
 *      Boxa creation, copy, destruction
 *           BOXA     *boxaCreate()
 *           BOXA     *boxaCopy()
 *           void      boxaDestroy()
 *
 *      Boxa array extension
 *           l_int32   boxaAddBox()
 *           l_int32   boxaExtendArray()
 *           l_int32   boxaExtendArrayToSize()
 *
 *      Boxa accessors
 *           l_int32   boxaGetCount()
 *           l_int32   boxaGetValidCount()
 *           BOX      *boxaGetBox()
 *           BOX      *boxaGetValidBox()
 *           NUMA     *boxaFindInvalidBoxes()
 *           l_int32   boxaGetBoxGeometry()
 *           l_int32   boxaIsFull()
 *
 *      Boxa array modifiers
 *           l_int32   boxaReplaceBox()
 *           l_int32   boxaInsertBox()
 *           l_int32   boxaRemoveBox()
 *           l_int32   boxaRemoveBoxAndSave()
 *           BOXA     *boxaSaveValid()
 *           l_int32   boxaInitFull()
 *           l_int32   boxaClear()
 *
 *      Boxaa creation, copy, destruction
 *           BOXAA    *boxaaCreate()
 *           BOXAA    *boxaaCopy()
 *           void      boxaaDestroy()
 *
 *      Boxaa array extension
 *           l_int32   boxaaAddBoxa()
 *           l_int32   boxaaExtendArray()
 *           l_int32   boxaaExtendArrayToSize()
 *
 *      Boxaa accessors
 *           l_int32   boxaaGetCount()
 *           l_int32   boxaaGetBoxCount()
 *           BOXA     *boxaaGetBoxa()
 *           BOX      *boxaaGetBox()
 *
 *      Boxaa array modifiers
 *           l_int32   boxaaInitFull()
 *           l_int32   boxaaExtendWithInit()
 *           l_int32   boxaaReplaceBoxa()
 *           l_int32   boxaaInsertBoxa()
 *           l_int32   boxaaRemoveBoxa()
 *           l_int32   boxaaAddBox()
 *
 *      Boxaa serialized I/O
 *           BOXAA    *boxaaReadFromFiles()
 *           BOXAA    *boxaaRead()
 *           BOXAA    *boxaaReadStream()
 *           BOXAA    *boxaaReadMem()
 *           l_int32   boxaaWrite()
 *           l_int32   boxaaWriteStream()
 *           l_int32   boxaaWriteMem()
 *
 *      Boxa serialized I/O
 *           BOXA     *boxaRead()
 *           BOXA     *boxaReadStream()
 *           BOXA     *boxaReadMem()
 *           l_int32   boxaWriteDebug()
 *           l_int32   boxaWrite()
 *           l_int32   boxaWriteStream()
 *           l_int32   boxaWriteStderr()
 *           l_int32   boxaWriteMem()
 *
 *      Box print (for debug)
 *           l_int32   boxPrintStreamInfo()
 *
 *   Most functions use only valid boxes, which are boxes that have both
 *   width and height > 0.  However, a few functions, such as
 *   boxaGetMedianVals() do not assume that all boxes are valid.  For any
 *   function that can use a boxa with invalid boxes, it is convenient
 *   to use these accessors:
 *       boxaGetValidCount()   :  count of valid boxes
 *       boxaGetValidBox()     :  returns NULL for invalid boxes
 * </pre>
 */

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

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

    /* Bounds on array sizes */
static const size_t  MaxBoxaPtrArraySize = 10000000;
static const size_t  MaxBoxaaPtrArraySize = 1000000;
static const size_t  InitialPtrArraySize = 20;      /*!< n'importe quoi */

/*---------------------------------------------------------------------*
 *                  Box creation, destruction and copy                 *
 *---------------------------------------------------------------------*/
/*!
 * \brief   boxCreate()
 *
 * \param[in]    x, y, w, h
 * \return  box, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) This clips the box to the +quad.  If no part of the
 *          box is in the +quad, this returns NULL.
 *      (2) We allow you to make a box with w = 0 and/or h = 0.
 *          This does not represent a valid region, but it is useful
 *          as a placeholder in a boxa for which the index of the
 *          box in the boxa is important.  This is an atypical
 *          situation; usually you want to put only valid boxes with
 *          nonzero width and height in a boxa.  If you have a boxa
 *          with invalid boxes, the accessor boxaGetValidBox()
 *          will return NULL on each invalid box.
 *      (3) If you want to create only valid boxes, use boxCreateValid(),
 *          which returns NULL if either w or h is 0.
 * </pre>
 */
BOX *
boxCreate(l_int32  x,
          l_int32  y,
          l_int32  w,
          l_int32  h)
{
BOX  *box;

    PROCNAME("boxCreate");

    if (w < 0 || h < 0)
        return (BOX *)ERROR_PTR("w and h not both >= 0", procName, NULL);
    if (x < 0) {  /* take part in +quad */
        w = w + x;
        x = 0;
        if (w <= 0)
            return (BOX *)ERROR_PTR("x < 0 and box off +quad", procName, NULL);
    }
    if (y < 0) {  /* take part in +quad */
        h = h + y;
        y = 0;
        if (h <= 0)
            return (BOX *)ERROR_PTR("y < 0 and box off +quad", procName, NULL);
    }

    box = (BOX *)LEPT_CALLOC(1, sizeof(BOX));
    boxSetGeometry(box, x, y, w, h);
    box->refcount = 1;
    return box;
}


/*!
 * \brief   boxCreateValid()
 *
 * \param[in]    x, y, w, h
 * \return  box, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) This returns NULL if either w = 0 or h = 0.
 * </pre>
 */
BOX *
boxCreateValid(l_int32  x,
               l_int32  y,
               l_int32  w,
               l_int32  h)
{
    PROCNAME("boxCreateValid");

    if (w <= 0 || h <= 0)
        return (BOX *)ERROR_PTR("w and h not both > 0", procName, NULL);
    return boxCreate(x, y, w, h);
}


/*!
 * \brief   boxCopy()
 *
 * \param[in]    box
 * \return  copy of box, or NULL on error
 */
BOX *
boxCopy(BOX  *box)
{
BOX  *boxc;

    PROCNAME("boxCopy");

    if (!box)
        return (BOX *)ERROR_PTR("box not defined", procName, NULL);

    boxc = boxCreate(box->x, box->y, box->w, box->h);
    return boxc;
}


/*!
 * \brief   boxClone()
 *
 * \param[in]    box
 * \return  ptr to same box, or NULL on error
 */
BOX *
boxClone(BOX  *box)
{

    PROCNAME("boxClone");

    if (!box)
        return (BOX *)ERROR_PTR("box not defined", procName, NULL);

    boxChangeRefcount(box, 1);
    return box;
}


/*!
 * \brief   boxDestroy()
 *
 * \param[in,out]   pbox     will be set to null before returning
 * \return  void
 *
 * <pre>
 * Notes:
 *      (1) Decrements the ref count and, if 0, destroys the box.
 *      (2) Always nulls the input ptr.
 * </pre>
 */
void
boxDestroy(BOX  **pbox)
{
BOX  *box;

    PROCNAME("boxDestroy");

    if (pbox == NULL) {
        L_WARNING("ptr address is null!\n", procName);
        return;
    }
    if ((box = *pbox) == NULL)
        return;

    boxChangeRefcount(box, -1);
    if (boxGetRefcount(box) <= 0)
        LEPT_FREE(box);
    *pbox = NULL;
}


/*---------------------------------------------------------------------*
 *                              Box accessors                          *
 *---------------------------------------------------------------------*/
/*!
 * \brief   boxGetGeometry()
 *
 * \param[in]    box
 * \param[out]   px, py, pw, ph [optional]  each can be null
 * \return  0 if OK, 1 on error
 */
l_ok
boxGetGeometry(BOX      *box,
               l_int32  *px,
               l_int32  *py,
               l_int32  *pw,
               l_int32  *ph)
{
    PROCNAME("boxGetGeometry");

    if (px) *px = 0;
    if (py) *py = 0;
    if (pw) *pw = 0;
    if (ph) *ph = 0;
    if (!box)
        return ERROR_INT("box not defined", procName, 1);
    if (px) *px = box->x;
    if (py) *py = box->y;
    if (pw) *pw = box->w;
    if (ph) *ph = box->h;
    return 0;
}


/*!
 * \brief   boxSetGeometry()
 *
 * \param[in]    box
 * \param[in]    x, y, w, h     [optional] use -1 to leave unchanged
 * \return  0 if OK, 1 on error
 */
l_ok
boxSetGeometry(BOX     *box,
               l_int32  x,
               l_int32  y,
               l_int32  w,
               l_int32  h)
{
    PROCNAME("boxSetGeometry");

    if (!box)
        return ERROR_INT("box not defined", procName, 1);
    if (x != -1) box->x = x;
    if (y != -1) box->y = y;
    if (w != -1) box->w = w;
    if (h != -1) box->h = h;
    return 0;
}


/*!
 * \brief   boxGetSideLocations()
 *
 * \param[in]    box
 * \param[out]   pl, pt, pr, pb     [optional] each can be null
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) All returned values are within the box.
 * </pre>
 */
l_ok
boxGetSideLocations(BOX      *box,
                    l_int32  *pl,
                    l_int32  *pr,
                    l_int32  *pt,
                    l_int32  *pb)
{
l_int32  x, y, w, h;

    PROCNAME("boxGetSideLocations");

    if (pl) *pl = 0;
    if (pr) *pr = 0;
    if (pt) *pt = 0;
    if (pb) *pb = 0;
    if (!box)
        return ERROR_INT("box not defined", procName, 1);

    boxGetGeometry(box, &x, &y, &w, &h);
    if (pl) *pl = x;
    if (pr) *pr = x + w - 1;
    if (pt) *pt = y;
    if (pb) *pb = y + h - 1;
    return 0;
}


/*!
 * \brief   boxSetSideLocations()
 *
 * \param[in]    box
 * \param[in]    l, r, t, b     [optional] use -1 to leave unchanged
 * \return  0 if OK, 1 on error
 */
l_ok
boxSetSideLocations(BOX     *box,
                    l_int32  l,
                    l_int32  r,
                    l_int32  t,
                    l_int32  b)
{
l_int32  x, y, w, h;

    PROCNAME("boxSetSideLocations");

    if (!box)
        return ERROR_INT("box not defined", procName, 1);
    x = (l != -1) ? l : box->x;
    w = (r != -1) ? r - x + 1 : box->x + box->w - x;
    y = (t != -1) ? t : box->y;
    h = (b != -1) ? b - y + 1 : box->y + box->h - y;
    boxSetGeometry(box, x, y, w, h);
    return 0;
}


/*!
 * \brief  Return the current reference count of %box
 *
 * \param[in]     box
 * \return   refcount
 */
l_int32
boxGetRefcount(BOX  *box)
{
    PROCNAME("boxGetRefcount");

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

    return box->refcount;
}

/*!
 * \brief  Adjust the current references count of %box by %delta
 *
 * \param[in]     box ptr to box
 * \param[in]     delta adjustment, usually -1 or 1
 * \return  0 if OK, 1 on error
 */
l_ok
boxChangeRefcount(BOX     *box,
                  l_int32  delta)
{
    PROCNAME("boxChangeRefcount");

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

    box->refcount += delta;
    return 0;
}


/*!
 * \brief   boxIsValid()
 *
 * \param[in]    box
 * \param[out]   pvalid    1 if valid; 0 otherwise
 * \return  0 if OK, 1 on error
 */
l_ok
boxIsValid(BOX      *box,
           l_int32  *pvalid)
{
    PROCNAME("boxIsValid");

    if (!pvalid)
        return ERROR_INT("&valid not defined", procName, 1);
    *pvalid = 0;
    if (!box)
        return ERROR_INT("box not defined", procName, 1);

    if (box->w > 0 && box->h > 0)
        *pvalid = 1;
    return 0;
}


/*---------------------------------------------------------------------*
 *             Boxa creation, destruction, copy, extension             *
 *---------------------------------------------------------------------*/
/*!
 * \brief   boxaCreate()
 *
 * \param[in]    n    initial number of ptrs; 0 for default
 * \return  boxa, or NULL on error
 */
BOXA *
boxaCreate(l_int32  n)
{
BOXA  *boxa;

    PROCNAME("boxaCreate");

    if (n <= 0 || n > MaxBoxaPtrArraySize)
        n = InitialPtrArraySize;

    boxa = (BOXA *)LEPT_CALLOC(1, sizeof(BOXA));
    boxa->n = 0;
    boxa->nalloc = n;
    boxa->refcount = 1;
    if ((boxa->box = (BOX **)LEPT_CALLOC(n, sizeof(BOX *))) == NULL) {
        boxaDestroy(&boxa);
        return (BOXA *)ERROR_PTR("boxa ptrs not made", procName, NULL);
    }
    return boxa;
}


/*!
 * \brief   boxaCopy()
 *
 * \param[in]    boxa
 * \param[in]    copyflag    L_COPY, L_CLONE, L_COPY_CLONE
 * \return  new boxa, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) See pix.h for description of the copyflag.
 *      (2) The copy-clone makes a new boxa that holds clones of each box.
 * </pre>
 */
BOXA *
boxaCopy(BOXA    *boxa,
         l_int32  copyflag)
{
l_int32  i;
BOX     *boxc;
BOXA    *boxac;

    PROCNAME("boxaCopy");

    if (!boxa)
        return (BOXA *)ERROR_PTR("boxa not defined", procName, NULL);

    if (copyflag == L_CLONE) {
        boxa->refcount++;
        return boxa;
    }

    if (copyflag != L_COPY && copyflag != L_COPY_CLONE)
        return (BOXA *)ERROR_PTR("invalid copyflag", procName, NULL);

    if ((boxac = boxaCreate(boxa->nalloc)) == NULL)
        return (BOXA *)ERROR_PTR("boxac not made", procName, NULL);
    for (i = 0; i < boxa->n; i++) {
        if (copyflag == L_COPY)
            boxc = boxaGetBox(boxa, i, L_COPY);
        else   /* copy-clone */
            boxc = boxaGetBox(boxa, i, L_CLONE);
        boxaAddBox(boxac, boxc, L_INSERT);
    }
    return boxac;
}


/*!
 * \brief   boxaDestroy()
 *
 * \param[in,out]   pboxa    will be set to null before returning
 * \return  void
 *
 * <pre>
 * Notes:
 *      (1) Decrements the ref count and, if 0, destroys the boxa.
 *      (2) Always nulls the input ptr.
 * </pre>
 */
void
boxaDestroy(BOXA  **pboxa)
{
l_int32  i;
BOXA    *boxa;

    PROCNAME("boxaDestroy");

    if (pboxa == NULL) {
        L_WARNING("ptr address is null!\n", procName);
        return;
    }

    if ((boxa = *pboxa) == NULL)
        return;

        /* Decrement the ref count.  If it is 0, destroy the boxa. */
    boxa->refcount--;
    if (boxa->refcount <= 0) {
        for (i = 0; i < boxa->n; i++)
            boxDestroy(&boxa->box[i]);
        LEPT_FREE(boxa->box);
        LEPT_FREE(boxa);
    }

    *pboxa = NULL;
}


/*!
 * \brief   boxaAddBox()
 *
 * \param[in]    boxa
 * \param[in]    box         to be added
 * \param[in]    copyflag    L_INSERT, L_COPY, L_CLONE
 * \return  0 if OK, 1 on error
 */
l_ok
boxaAddBox(BOXA    *boxa,
           BOX     *box,
           l_int32  copyflag)
{
l_int32  n;
BOX     *boxc;

    PROCNAME("boxaAddBox");

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

    if (copyflag == L_INSERT)
        boxc = box;
    else if (copyflag == L_COPY)
        boxc = boxCopy(box);
    else if (copyflag == L_CLONE)
        boxc = boxClone(box);
    else
        return ERROR_INT("invalid copyflag", procName, 1);
    if (!boxc)
        return ERROR_INT("boxc not made", procName, 1);

    n = boxaGetCount(boxa);
    if (n >= boxa->nalloc) {
        if (boxaExtendArray(boxa)) {
            if (copyflag != L_INSERT)
                boxDestroy(&boxc);
            return ERROR_INT("extension failed", procName, 1);
        }
    }
    boxa->box[n] = boxc;
    boxa->n++;
    return 0;
}


/*!
 * \brief   boxaExtendArray()
 *
 * \param[in]    boxa
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Reallocs with doubled size of ptr array.
 * </pre>
 */
l_ok
boxaExtendArray(BOXA  *boxa)
{
    PROCNAME("boxaExtendArray");

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

    return boxaExtendArrayToSize(boxa, 2 * boxa->nalloc);
}


/*!
 * \brief   boxaExtendArrayToSize()
 *
 * \param[in]    boxa
 * \param[in]    size     new size of boxa ptr array
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) If necessary, reallocs new boxa ptr array to %size.
 *      (2) The max number of box ptrs is 10M.
 * </pre>
 */
l_ok
boxaExtendArrayToSize(BOXA   *boxa,
                      size_t  size)
{
size_t  oldsize, newsize;

    PROCNAME("boxaExtendArrayToSize");

    if (!boxa)
        return ERROR_INT("boxa not defined", procName, 1);
    if (boxa->nalloc > MaxBoxaPtrArraySize)  /* belt & suspenders */
        return ERROR_INT("boxa has too many ptrs", procName, 1);
    if (size > MaxBoxaPtrArraySize)
        return ERROR_INT("size > 10M box ptrs; too large", procName, 1);
    if (size <= boxa->nalloc) {
        L_INFO("size too small; no extension\n", procName);
        return 0;
    }

    oldsize = boxa->nalloc * sizeof(BOX *);
    newsize = size * sizeof(BOX *);
    if ((boxa->box = (BOX **)reallocNew((void **)&boxa->box,
                                        oldsize, newsize)) == NULL)
        return ERROR_INT("new ptr array not returned", procName, 1);
    boxa->nalloc = size;
    return 0;
}


/*---------------------------------------------------------------------*
 *                             Boxa accessors                          *
 *---------------------------------------------------------------------*/
/*!
 * \brief   boxaGetCount()
 *
 * \param[in]    boxa
 * \return  count of all boxes; 0 if no boxes or on error
 */
l_int32
boxaGetCount(BOXA  *boxa)
{
    PROCNAME("boxaGetCount");

    if (!boxa)
        return ERROR_INT("boxa not defined", procName, 0);
    return boxa->n;
}


/*!
 * \brief   boxaGetValidCount()
 *
 * \param[in]    boxa
 * \return  count of valid boxes; 0 if no valid boxes or on error
 */
l_int32
boxaGetValidCount(BOXA  *boxa)
{
l_int32  n, i, w, h, count;

    PROCNAME("boxaGetValidCount");

    if (!boxa)
        return ERROR_INT("boxa not defined", procName, 0);

    n = boxaGetCount(boxa);
    for (i = 0, count = 0; i < n; i++) {
        boxaGetBoxGeometry(boxa, i, NULL, NULL, &w, &h);
        if (w > 0 && h > 0)
            count++;
    }
    return count;
}


/*!
 * \brief   boxaGetBox()
 *
 * \param[in]    boxa
 * \param[in]    index        to the index-th box
 * \param[in]    accessflag   L_COPY or L_CLONE
 * \return  box, or NULL on error
 */
BOX *
boxaGetBox(BOXA    *boxa,
           l_int32  index,
           l_int32  accessflag)
{
    PROCNAME("boxaGetBox");

    if (!boxa)
        return (BOX *)ERROR_PTR("boxa not defined", procName, NULL);
    if (index < 0 || index >= boxa->n)
        return (BOX *)ERROR_PTR("index not valid", procName, NULL);

    if (accessflag == L_COPY)
        return boxCopy(boxa->box[index]);
    else if (accessflag == L_CLONE)
        return boxClone(boxa->box[index]);
    else
        return (BOX *)ERROR_PTR("invalid accessflag", procName, NULL);
}


/*!
 * \brief   boxaGetValidBox()
 *
 * \param[in]    boxa
 * \param[in]    index        to the index-th box
 * \param[in]    accessflag   L_COPY or L_CLONE
 * \return  box, or NULL if box is not valid or on error
 *
 * <pre>
 * Notes:
 *      (1) This returns NULL for an invalid box in a boxa.
 *          For a box to be valid, both the width and height must be > 0.
 *      (2) We allow invalid boxes, with w = 0 or h = 0, as placeholders
 *          in boxa for which the index of the box in the boxa is important.
 *          This is an atypical situation; usually you want to put only
 *          valid boxes in a boxa.
 * </pre>
 */
BOX *
boxaGetValidBox(BOXA    *boxa,
                l_int32  index,
                l_int32  accessflag)
{
l_int32  w, h;
BOX     *box;

    PROCNAME("boxaGetValidBox");

    if (!boxa)
        return (BOX *)ERROR_PTR("boxa not defined", procName, NULL);

    if ((box = boxaGetBox(boxa, index, accessflag)) == NULL)
        return (BOX *)ERROR_PTR("box not returned", procName, NULL);
    boxGetGeometry(box, NULL, NULL, &w, &h);
    if (w <= 0 || h <= 0)  /* not valid, but not necessarily an error */
        boxDestroy(&box);
    return box;
}


/*!
 * \brief   boxaFindInvalidBoxes()
 *
 * \param[in]    boxa
 * \return  na   numa of invalid boxes; NULL if there are none or on error
 */
NUMA *
boxaFindInvalidBoxes(BOXA  *boxa)
{
l_int32  i, n, w, h;
NUMA    *na;

    PROCNAME("boxaFindInvalidBoxes");

    if (!boxa)
        return (NUMA *)ERROR_PTR("boxa not defined", procName, NULL);

    n = boxaGetCount(boxa);
    if (boxaGetValidCount(boxa) == n)
        return NULL;

    na = numaMakeConstant(0, n);
    for (i = 0; i < n; i++) {
        boxaGetBoxGeometry(boxa, i, NULL, NULL, &w, &h);
        if (w == 0 || h == 0)
            numaSetValue(na, i, 1);
    }
    return na;
}


/*!
 * \brief   boxaGetBoxGeometry()
 *
 * \param[in]    boxa
 * \param[in]    index            to the index-th box
 * \param[out]   px, py, pw, ph   [optional] each can be null
 * \return  0 if OK, 1 on error
 */
l_ok
boxaGetBoxGeometry(BOXA     *boxa,
                   l_int32   index,
                   l_int32  *px,
                   l_int32  *py,
                   l_int32  *pw,
                   l_int32  *ph)
{
BOX  *box;

    PROCNAME("boxaGetBoxGeometry");

    if (px) *px = 0;
    if (py) *py = 0;
    if (pw) *pw = 0;
    if (ph) *ph = 0;
    if (!boxa)
        return ERROR_INT("boxa not defined", procName, 1);
    if (index < 0 || index >= boxa->n)
        return ERROR_INT("index not valid", procName, 1);

    if ((box = boxaGetBox(boxa, index, L_CLONE)) == NULL)
        return ERROR_INT("box not found!", procName, 1);
    boxGetGeometry(box, px, py, pw, ph);
    boxDestroy(&box);
    return 0;
}


/*!
 * \brief   boxaIsFull()
 *
 * \param[in]    boxa
 * \param[out]   pfull    1 if boxa is full; 0 otherwise
 * \return  0 if OK, 1 on error
 */
l_ok
boxaIsFull(BOXA     *boxa,
           l_int32  *pfull)
{
l_int32  i, n, full;
BOX     *box;

    PROCNAME("boxaIsFull");

    if (!pfull)
        return ERROR_INT("&full not defined", procName, 1);
    *pfull = 0;
    if (!boxa)
        return ERROR_INT("boxa not defined", procName, 1);

    n = boxaGetCount(boxa);
    full = 1;
    for (i = 0; i < n; i++) {
        if ((box = boxaGetBox(boxa, i, L_CLONE)) == NULL) {
            full = 0;
            break;
        }
        boxDestroy(&box);
    }
    *pfull = full;
    return 0;
}


/*---------------------------------------------------------------------*
 *                        Boxa array modifiers                         *
 *---------------------------------------------------------------------*/
/*!
 * \brief   boxaReplaceBox()
 *
 * \param[in]    boxa
 * \param[in]    index     to the index-th box
 * \param[in]    box       insert this box to replace existing one
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) In-place replacement of one box; the input %box is now
 *          owned by the boxa.
 *      (2) The previous box at that location, if any, is destroyed.
 * </pre>
 */
l_ok
boxaReplaceBox(BOXA    *boxa,
               l_int32  index,
               BOX     *box)
{
    PROCNAME("boxaReplaceBox");

    if (!boxa)
        return ERROR_INT("boxa not defined", procName, 1);
    if (index < 0 || index >= boxa->n)
        return ERROR_INT("index not valid", procName, 1);
    if (!box)
        return ERROR_INT("box not defined", procName, 1);

    boxDestroy(&(boxa->box[index]));
    boxa->box[index] = box;
    return 0;
}


/*!
 * \brief   boxaInsertBox()
 *
 * \param[in]    boxa
 * \param[in]    index    location in boxa to insert new value
 * \param[in]    box      new box to be inserted; the boxa now owns it
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This shifts box[i] --> box[i + 1] for all i >= index,
 *          and then inserts box as box[index].
 *      (2) To insert at the beginning of the array, set index = 0.
 *      (3) To append to the array, it's easier to use boxaAddBox().
 *      (4) This should not be used repeatedly to insert into large arrays,
 *          because the function is O(n).
 * </pre>
 */
l_ok
boxaInsertBox(BOXA    *boxa,
              l_int32  index,
              BOX     *box)
{
l_int32  i, n;
BOX    **array;

    PROCNAME("boxaInsertBox");

    if (!boxa)
        return ERROR_INT("boxa not defined", procName, 1);
    n = boxaGetCount(boxa);
    if (index < 0 || index > n) {
        L_ERROR("index %d not in [0,...,%d]\n", procName, index, n);
        return 1;
    }
    if (!box)
        return ERROR_INT("box not defined", procName, 1);

    if (n >= boxa->nalloc) {
        if (boxaExtendArray(boxa))
            return ERROR_INT("extension failed", procName, 1);
    }
    array = boxa->box;
    boxa->n++;
    for (i = n; i > index; i--)
        array[i] = array[i - 1];
    array[index] = box;
    return 0;
}


/*!
 * \brief   boxaRemoveBox()
 *
 * \param[in]    boxa
 * \param[in]    index    of box to be removed and destroyed
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This removes box[index] and then shifts
 *          box[i] --> box[i - 1] for all i > index.
 *      (2) It should not be used repeatedly to remove boxes from
 *          large arrays, because the function is O(n).
 * </pre>
 */
l_ok
boxaRemoveBox(BOXA    *boxa,
              l_int32  index)
{
    return boxaRemoveBoxAndSave(boxa, index, NULL);
}


/*!
 * \brief   boxaRemoveBoxAndSave()
 *
 * \param[in]    boxa
 * \param[in]    index     of box to be removed
 * \param[out]   pbox      [optional] removed box
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This removes box[index] and then shifts
 *          box[i] --> box[i - 1] for all i > index.
 *      (2) It should not be used repeatedly to remove boxes from
 *          large arrays, because the function is O(n).
 * </pre>
 */
l_ok
boxaRemoveBoxAndSave(BOXA    *boxa,
                     l_int32  index,
                     BOX    **pbox)
{
l_int32  i, n;
BOX    **array;

    PROCNAME("boxaRemoveBoxAndSave");

    if (pbox) *pbox = NULL;
    if (!boxa)
        return ERROR_INT("boxa not defined", procName, 1);
    n = boxaGetCount(boxa);
    if (index < 0 || index >= n) {
        L_ERROR("index %d not in [0,...,%d]\n", procName, index, n - 1);
        return 1;
    }

    if (pbox)
        *pbox = boxaGetBox(boxa, index, L_CLONE);
    array = boxa->box;
    boxDestroy(&array[index]);
    for (i = index + 1; i < n; i++)
        array[i - 1] = array[i];
    array[n - 1] = NULL;
    boxa->n--;

    return 0;
}


/*!
 * \brief   boxaSaveValid()
 *
 * \param[in]    boxas
 * \param[in]    copyflag    L_COPY or L_CLONE
 * \return  boxad if OK, NULL on error
 *
 * <pre>
 * Notes:
 *      (1) This makes a copy/clone of each valid box.
 * </pre>
 */
BOXA *
boxaSaveValid(BOXA    *boxas,
              l_int32  copyflag)
{
l_int32  i, n;
BOX     *box;
BOXA    *boxad;

    PROCNAME("boxaSaveValid");

    if (!boxas)
        return (BOXA *)ERROR_PTR("boxas not defined", procName, NULL);
    if (copyflag != L_COPY && copyflag != L_CLONE)
        return (BOXA *)ERROR_PTR("invalid copyflag", procName, NULL);

    n = boxaGetCount(boxas);
    boxad = boxaCreate(n);
    for (i = 0; i < n; i++) {
        if ((box = boxaGetValidBox(boxas, i, copyflag)) != NULL)
            boxaAddBox(boxad, box, L_INSERT);
    }

    return boxad;
}


/*!
 * \brief   boxaInitFull()
 *
 * \param[in]    boxa    typically empty
 * \param[in]    box     [optional] to be replicated into the entire ptr array
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This initializes a boxa by filling up the entire box ptr array
 *          with copies of %box.  If %box == NULL, use a placeholder box
 *          of zero size.  Any existing boxes are destroyed.
 *          After this opepration, the number of boxes is equal to
 *          the number of allocated ptrs.
 *      (2) Note that we use boxaReplaceBox() instead of boxaInsertBox().
 *          They both have the same effect when inserting into a NULL ptr
 *          in the boxa ptr array:
 *      (3) Example usage.  This function is useful to prepare for a
 *          random insertion (or replacement) of boxes into a boxa.
 *          To randomly insert boxes into a boxa, up to some index "max":
 *             Boxa *boxa = boxaCreate(max);
 *             boxaInitFull(boxa, NULL);
 *          If you want placeholder boxes of non-zero size:
 *             Boxa *boxa = boxaCreate(max);
 *             Box *box = boxCreate(...);
 *             boxaInitFull(boxa, box);
 *             boxDestroy(&box);
 *          If we have an existing boxa with a smaller ptr array, it can
 *          be reused for up to max boxes:
 *             boxaExtendArrayToSize(boxa, max);
 *             boxaInitFull(boxa, NULL);
 *          The initialization allows the boxa to always be properly
 *          filled, even if all the boxes are not later replaced.
 *          If you want to know which boxes have been replaced,
 *          and you initialized with invalid zero-sized boxes,
 *          use boxaGetValidBox() to return NULL for the invalid boxes.
 * </pre>
 */
l_ok
boxaInitFull(BOXA  *boxa,
             BOX   *box)
{
l_int32  i, n;
BOX     *boxt;

    PROCNAME("boxaInitFull");

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

    n = boxa->nalloc;
    boxa->n = n;
    for (i = 0; i < n; i++) {
        if (box)
            boxt = boxCopy(box);
        else
            boxt = boxCreate(0, 0, 0, 0);
        boxaReplaceBox(boxa, i, boxt);
    }
    return 0;
}


/*!
 * \brief   boxaClear()
 *
 * \param[in]    boxa
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This destroys all boxes in the boxa, setting the ptrs
 *          to null.  The number of allocated boxes, n, is set to 0.
 * </pre>
 */
l_ok
boxaClear(BOXA  *boxa)
{
l_int32  i, n;

    PROCNAME("boxaClear");

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

    n = boxaGetCount(boxa);
    for (i = 0; i < n; i++)
        boxDestroy(&boxa->box[i]);
    boxa->n = 0;
    return 0;
}


/*--------------------------------------------------------------------------*
 *                     Boxaa creation, destruction                          *
 *--------------------------------------------------------------------------*/
/*!
 * \brief   boxaaCreate()
 *
 * \param[in]    n     size of boxa ptr array to be alloc'd; 0 for default
 * \return  baa, or NULL on error
 */
BOXAA *
boxaaCreate(l_int32  n)
{
BOXAA  *baa;

    PROCNAME("boxaaCreate");

    if (n <= 0 || n > MaxBoxaaPtrArraySize)
        n = InitialPtrArraySize;

    baa = (BOXAA *)LEPT_CALLOC(1, sizeof(BOXAA));
    if ((baa->boxa = (BOXA **)LEPT_CALLOC(n, sizeof(BOXA *))) == NULL) {
        boxaaDestroy(&baa);
        return (BOXAA *)ERROR_PTR("boxa ptr array not made", procName, NULL);
    }
    baa->nalloc = n;
    baa->n = 0;
    return baa;
}


/*!
 * \brief   boxaaCopy()
 *
 * \param[in]    baas       input boxaa to be copied
 * \param[in]    copyflag   L_COPY, L_CLONE
 * \return  baad new boxaa, composed of copies or clones of the boxa
 *                    in baas, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) L_COPY makes a copy of each boxa in baas.
 *          L_CLONE makes a clone of each boxa in baas.
 * </pre>
 */
BOXAA *
boxaaCopy(BOXAA   *baas,
          l_int32  copyflag)
{
l_int32  i, n;
BOXA    *boxa;
BOXAA   *baad;

    PROCNAME("boxaaCopy");

    if (!baas)
        return (BOXAA *)ERROR_PTR("baas not defined", procName, NULL);
    if (copyflag != L_COPY && copyflag != L_CLONE)
        return (BOXAA *)ERROR_PTR("invalid copyflag", procName, NULL);

    n = boxaaGetCount(baas);
    baad = boxaaCreate(n);
    for (i = 0; i < n; i++) {
        boxa = boxaaGetBoxa(baas, i, copyflag);
        boxaaAddBoxa(baad, boxa, L_INSERT);
    }

    return baad;
}


/*!
 * \brief   boxaaDestroy()
 *
 * \param[in,out]   pbaa     will be set to null before returning
 */
void
boxaaDestroy(BOXAA  **pbaa)
{
l_int32  i;
BOXAA   *baa;

    PROCNAME("boxaaDestroy");

    if (pbaa == NULL) {
        L_WARNING("ptr address is NULL!\n", procName);
        return;
    }

    if ((baa = *pbaa) == NULL)
        return;

    for (i = 0; i < baa->n; i++)
        boxaDestroy(&baa->boxa[i]);
    LEPT_FREE(baa->boxa);
    LEPT_FREE(baa);
    *pbaa = NULL;
}



/*--------------------------------------------------------------------------*
 *                              Add Boxa to Boxaa                           *
 *--------------------------------------------------------------------------*/
/*!
 * \brief   boxaaAddBoxa()
 *
 * \param[in]    baa
 * \param[in]    ba         to be added
 * \param[in]    copyflag   L_INSERT, L_COPY, L_CLONE
 * \return  0 if OK, 1 on error
 */
l_ok
boxaaAddBoxa(BOXAA   *baa,
             BOXA    *ba,
             l_int32  copyflag)
{
l_int32  n;
BOXA    *bac;

    PROCNAME("boxaaAddBoxa");

    if (!baa)
        return ERROR_INT("baa not defined", procName, 1);
    if (!ba)
        return ERROR_INT("ba not defined", procName, 1);
    if (copyflag != L_INSERT && copyflag != L_COPY && copyflag != L_CLONE)
        return ERROR_INT("invalid copyflag", procName, 1);

    if (copyflag == L_INSERT)
        bac = ba;
    else
        bac = boxaCopy(ba, copyflag);

    n = boxaaGetCount(baa);
    if (n >= baa->nalloc) {
        if (boxaaExtendArray(baa))
            return ERROR_INT("extension failed", procName, 1);
    }
    baa->boxa[n] = bac;
    baa->n++;
    return 0;
}


/*!
 * \brief   boxaaExtendArray()
 *
 * \param[in]    baa
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Doubles the size of the boxa ptr array.
 *      (2) The max number of boxa ptrs is 1 million.
 * </pre>
 */
l_ok
boxaaExtendArray(BOXAA  *baa)
{
    PROCNAME("boxaaExtendArray");

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

    return boxaaExtendArrayToSize(baa, 2 * baa->nalloc);
}


/*!
 * \brief   boxaaExtendArrayToSize()
 *
 * \param[in]    baa
 * \param[in]    size     new size of boxa array
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) If necessary, reallocs the boxa ptr array to %size.
 *      (2) %size limited to 1M boxa ptrs.
 * </pre>
 */
l_ok
boxaaExtendArrayToSize(BOXAA   *baa,
                       l_int32  size)
{
size_t  oldsize, newsize;

    PROCNAME("boxaaExtendArrayToSize");

    if (!baa)
        return ERROR_INT("baa not defined", procName, 1);
    if (baa->nalloc > MaxBoxaaPtrArraySize)  /* belt & suspenders */
        return ERROR_INT("baa has too many ptrs", procName, 1);
    if (size > MaxBoxaaPtrArraySize)
        return ERROR_INT("size > 1M boxa ptrs; too large", procName, 1);
    if (size <= baa->nalloc) {
        L_INFO("size too small; no extension\n", procName);
        return 0;
    }

    oldsize = baa->nalloc * sizeof(BOXA *);
    newsize = size * sizeof(BOXA *);
    if ((baa->boxa = (BOXA **)reallocNew((void **)&baa->boxa,
                                         oldsize, newsize)) == NULL)
        return ERROR_INT("new ptr array not returned", procName, 1);
    baa->nalloc = size;
    return 0;
}


/*----------------------------------------------------------------------*
 *                           Boxaa accessors                            *
 *----------------------------------------------------------------------*/
/*!
 * \brief   boxaaGetCount()
 *
 * \param[in]    baa
 * \return  count number of boxa, or 0 if no boxa or on error
 */
l_int32
boxaaGetCount(BOXAA  *baa)
{
    PROCNAME("boxaaGetCount");

    if (!baa)
        return ERROR_INT("baa not defined", procName, 0);
    return baa->n;
}


/*!
 * \brief   boxaaGetBoxCount()
 *
 * \param[in]    baa
 * \return  count number of boxes, or 0 if no boxes or on error
 */
l_int32
boxaaGetBoxCount(BOXAA  *baa)
{
BOXA    *boxa;
l_int32  n, sum, i;

    PROCNAME("boxaaGetBoxCount");

    if (!baa)
        return ERROR_INT("baa not defined", procName, 0);

    n = boxaaGetCount(baa);
    for (sum = 0, i = 0; i < n; i++) {
        boxa = boxaaGetBoxa(baa, i, L_CLONE);
        sum += boxaGetCount(boxa);
        boxaDestroy(&boxa);
    }

    return sum;
}


/*!
 * \brief   boxaaGetBoxa()
 *
 * \param[in]    baa
 * \param[in]    index        to the index-th boxa
 * \param[in]    accessflag   L_COPY or L_CLONE
 * \return  boxa, or NULL on error
 */
BOXA *
boxaaGetBoxa(BOXAA   *baa,
             l_int32  index,
             l_int32  accessflag)
{
l_int32  n;

    PROCNAME("boxaaGetBoxa");

    if (!baa)
        return (BOXA *)ERROR_PTR("baa not defined", procName, NULL);
    n = boxaaGetCount(baa);
    if (index < 0 || index >= n)
        return (BOXA *)ERROR_PTR("index not valid", procName, NULL);
    if (accessflag != L_COPY && accessflag != L_CLONE)
        return (BOXA *)ERROR_PTR("invalid accessflag", procName, NULL);

    return boxaCopy(baa->boxa[index], accessflag);
}


/*!
 * \brief   boxaaGetBox()
 *
 * \param[in]    baa
 * \param[in]    iboxa        index into the boxa array in the boxaa
 * \param[in]    ibox         index into the box array in the boxa
 * \param[in]    accessflag   L_COPY or L_CLONE
 * \return  box, or NULL on error
 */
BOX *
boxaaGetBox(BOXAA   *baa,
            l_int32  iboxa,
            l_int32  ibox,
            l_int32  accessflag)
{
BOX   *box;
BOXA  *boxa;

    PROCNAME("boxaaGetBox");

    if ((boxa = boxaaGetBoxa(baa, iboxa, L_CLONE)) == NULL)
        return (BOX *)ERROR_PTR("boxa not retrieved", procName, NULL);
    if ((box = boxaGetBox(boxa, ibox, accessflag)) == NULL)
        L_ERROR("box not retrieved\n", procName);
    boxaDestroy(&boxa);
    return box;
}


/*----------------------------------------------------------------------*
 *                           Boxaa array modifiers                      *
 *----------------------------------------------------------------------*/
/*!
 * \brief   boxaaInitFull()
 *
 * \param[in]    baa      typically empty
 * \param[in]    boxa     to be replicated into the entire ptr array
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This initializes a boxaa by filling up the entire boxa ptr array
 *          with copies of %boxa.  Any existing boxa are destroyed.
 *          After this operation, the number of boxa is equal to
 *          the number of allocated ptrs.
 *      (2) Note that we use boxaaReplaceBox() instead of boxaInsertBox().
 *          They both have the same effect when inserting into a NULL ptr
 *          in the boxa ptr array
 *      (3) Example usage.  This function is useful to prepare for a
 *          random insertion (or replacement) of boxa into a boxaa.
 *          To randomly insert boxa into a boxaa, up to some index "max":
 *             Boxaa *baa = boxaaCreate(max);
 *               // initialize the boxa
 *             Boxa *boxa = boxaCreate(...);
 *             ...  [optionally fix with boxes]
 *             boxaaInitFull(baa, boxa);
 *          A typical use is to initialize the array with empty boxa,
 *          and to replace only a subset that must be aligned with
 *          something else, such as a pixa.
 * </pre>
 */
l_ok
boxaaInitFull(BOXAA  *baa,
              BOXA   *boxa)
{
l_int32  i, n;
BOXA    *boxat;

    PROCNAME("boxaaInitFull");

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

    n = baa->nalloc;
    baa->n = n;
    for (i = 0; i < n; i++) {
        boxat = boxaCopy(boxa, L_COPY);
        boxaaReplaceBoxa(baa, i, boxat);
    }
    return 0;
}


/*!
 * \brief   boxaaExtendWithInit()
 *
 * \param[in]    baa
 * \param[in]    maxindex
 * \param[in]    boxa       to be replicated into the extended ptr array
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This should be used on an existing boxaa that has been
 *          fully loaded with boxa.  It then extends the boxaa,
 *          loading all the additional ptrs with copies of boxa.
 *          Typically, boxa will be empty.
 * </pre>
 */
l_ok
boxaaExtendWithInit(BOXAA   *baa,
                    l_int32  maxindex,
                    BOXA    *boxa)
{
l_int32  i, n;

    PROCNAME("boxaaExtendWithInit");

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

        /* Extend the ptr array if necessary */
    n = boxaaGetCount(baa);
    if (maxindex < n) return 0;
    if (boxaaExtendArrayToSize(baa, maxindex + 1))
        return ERROR_INT("extension failed", procName, 1);

        /* Fill the new entries with copies of boxa */
    for (i = n; i <= maxindex; i++)
        boxaaAddBoxa(baa, boxa, L_COPY);
    return 0;
}


/*!
 * \brief   boxaaReplaceBoxa()
 *
 * \param[in]    baa
 * \param[in]    index    to the index-th boxa
 * \param[in]    boxa     insert and replace any existing one
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Any existing boxa is destroyed, and the input one
 *          is inserted in its place.
 *      (2) If the index is invalid, return 1 (error)
 * </pre>
 */
l_ok
boxaaReplaceBoxa(BOXAA   *baa,
                 l_int32  index,
                 BOXA    *boxa)
{
l_int32  n;

    PROCNAME("boxaaReplaceBoxa");

    if (!baa)
        return ERROR_INT("baa not defined", procName, 1);
    if (!boxa)
        return ERROR_INT("boxa not defined", procName, 1);
    n = boxaaGetCount(baa);
    if (index < 0 || index >= n)
        return ERROR_INT("index not valid", procName, 1);

    boxaDestroy(&baa->boxa[index]);
    baa->boxa[index] = boxa;
    return 0;
}


/*!
 * \brief   boxaaInsertBoxa()
 *
 * \param[in]    baa
 * \param[in]    index    location in boxaa to insert new boxa
 * \param[in]    boxa     new boxa to be inserted
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This shifts boxa[i] --> boxa[i + 1] for all i >= index,
 *          and then inserts boxa as boxa[index].
 *      (2) To insert at the beginning of the array, set index = 0.
 *      (3) To append to the array, it's easier to use boxaaAddBoxa().
 *      (4) This should not be used repeatedly to insert into large arrays,
 *          because the function is O(n).
 * </pre>
 */
l_ok
boxaaInsertBoxa(BOXAA   *baa,
                l_int32  index,
                BOXA    *boxa)
{
l_int32  i, n;
BOXA   **array;

    PROCNAME("boxaaInsertBoxa");

    if (!baa)
        return ERROR_INT("baa not defined", procName, 1);
    n = boxaaGetCount(baa);
    if (index < 0 || index > n) {
        L_ERROR("index %d not in [0,...,%d]\n", procName, index, n);
        return 1;
    }
    if (!boxa)
        return ERROR_INT("boxa not defined", procName, 1);

    if (n >= baa->nalloc) {
        if (boxaaExtendArray(baa))
            return ERROR_INT("extension failed", procName, 1);
    }
    array = baa->boxa;
    baa->n++;
    for (i = n; i > index; i--)
        array[i] = array[i - 1];
    array[index] = boxa;
    return 0;
}


/*!
 * \brief   boxaaRemoveBoxa()
 *
 * \param[in]    baa
 * \param[in]    index   of the boxa to be removed and destroyed
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This removes boxa[index] and then shifts
 *          boxa[i] --> boxa[i - 1] for all i > index.
 *      (2) The removed boxaa is destroyed.
 *      (2) This should not be used repeatedly on large arrays,
 *          because the function is O(n).
 * </pre>
 */
l_ok
boxaaRemoveBoxa(BOXAA   *baa,
                l_int32  index)
{
l_int32  i, n;
BOXA   **array;

    PROCNAME("boxaaRemoveBox");

    if (!baa)
        return ERROR_INT("baa not defined", procName, 1);
    n = boxaaGetCount(baa);
    if (index < 0 || index >= n)
        return ERROR_INT("index not valid", procName, 1);

    array = baa->boxa;
    boxaDestroy(&array[index]);
    for (i = index + 1; i < n; i++)
        array[i - 1] = array[i];
    array[n - 1] = NULL;
    baa->n--;

    return 0;
}


/*!
 * \brief   boxaaAddBox()
 *
 * \param[in]    baa
 * \param[in]    index       of boxa with boxaa
 * \param[in]    box         to be added
 * \param[in]    accessflag  L_INSERT, L_COPY or L_CLONE
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Adds to an existing boxa only.
 * </pre>
 */
l_ok
boxaaAddBox(BOXAA   *baa,
            l_int32  index,
            BOX     *box,
            l_int32  accessflag)
{
l_int32  n;
BOXA    *boxa;
    PROCNAME("boxaaAddBox");

    if (!baa)
        return ERROR_INT("baa not defined", procName, 1);
    n = boxaaGetCount(baa);
    if (index < 0 || index >= n)
        return ERROR_INT("index not valid", procName, 1);
    if (accessflag != L_INSERT && accessflag != L_COPY && accessflag != L_CLONE)
        return ERROR_INT("invalid accessflag", procName, 1);

    boxa = boxaaGetBoxa(baa, index, L_CLONE);
    boxaAddBox(boxa, box, accessflag);
    boxaDestroy(&boxa);
    return 0;
}


/*---------------------------------------------------------------------*
 *                        Boxaa serialized I/O                         *
 *---------------------------------------------------------------------*/
/*!
 * \brief   boxaaReadFromFiles()
 *
 * \param[in]    dirname   directory
 * \param[in]    substr    [optional] substring filter on filenames; can be NULL
 * \param[in]    first     0-based
 * \param[in]    nfiles    use 0 for everything from %first to the end
 * \return  baa, or NULL on error or if no boxa files are found.
 *
 * <pre>
 * Notes:
 *      (1) The files must be serialized boxa files (e.g., *.ba).
 *          If some files cannot be read, warnings are issued.
 *      (2) Use %substr to filter filenames in the directory.  If
 *          %substr == NULL, this takes all files.
 *      (3) After filtering, use %first and %nfiles to select
 *          a contiguous set of files, that have been lexically
 *          sorted in increasing order.
 * </pre>
 */
BOXAA *
boxaaReadFromFiles(const char  *dirname,
                   const char  *substr,
                   l_int32      first,
                   l_int32      nfiles)
{
char    *fname;
l_int32  i, n;
BOXA    *boxa;
BOXAA   *baa;
SARRAY  *sa;

  PROCNAME("boxaaReadFromFiles");

  if (!dirname)
      return (BOXAA *)ERROR_PTR("dirname not defined", procName, NULL);

  sa = getSortedPathnamesInDirectory(dirname, substr, first, nfiles);
  if (!sa || ((n = sarrayGetCount(sa)) == 0)) {
      sarrayDestroy(&sa);
      return (BOXAA *)ERROR_PTR("no pixa files found", procName, NULL);
  }

  baa = boxaaCreate(n);
  for (i = 0; i < n; i++) {
      fname = sarrayGetString(sa, i, L_NOCOPY);
      if ((boxa = boxaRead(fname)) == NULL) {
          L_ERROR("boxa not read for %d-th file", procName, i);
          continue;
      }
      boxaaAddBoxa(baa, boxa, L_INSERT);
  }

  sarrayDestroy(&sa);
  return baa;
}


/*!
 * \brief   boxaaRead()
 *
 * \param[in]    filename
 * \return  boxaa, or NULL on error
 */
BOXAA *
boxaaRead(const char  *filename)
{
FILE   *fp;
BOXAA  *baa;

    PROCNAME("boxaaRead");

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

    if ((fp = fopenReadStream(filename)) == NULL)
        return (BOXAA *)ERROR_PTR("stream not opened", procName, NULL);
    baa = boxaaReadStream(fp);
    fclose(fp);
    if (!baa)
        return (BOXAA *)ERROR_PTR("boxaa not read", procName, NULL);
    return baa;
}


/*!
 * \brief   boxaaReadStream()
 *
 * \param[in]    fp    input file stream
 * \return  boxaa, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) It is OK for the boxaa to be empty (n == 0).
 * </pre>
 */
BOXAA *
boxaaReadStream(FILE  *fp)
{
l_int32  n, i, x, y, w, h, version;
l_int32  ignore;
BOXA    *boxa;
BOXAA   *baa;

    PROCNAME("boxaaReadStream");

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

    if (fscanf(fp, "\nBoxaa Version %d\n", &version) != 1)
        return (BOXAA *)ERROR_PTR("not a boxaa file", procName, NULL);
    if (version != BOXAA_VERSION_NUMBER)
        return (BOXAA *)ERROR_PTR("invalid boxa version", procName, NULL);
    if (fscanf(fp, "Number of boxa = %d\n", &n) != 1)
        return (BOXAA *)ERROR_PTR("not a boxaa file", procName, NULL);
    if (n < 0)
        return (BOXAA *)ERROR_PTR("num boxa ptrs < 0", procName, NULL);
    if (n > MaxBoxaaPtrArraySize)
        return (BOXAA *)ERROR_PTR("too many boxa ptrs", procName, NULL);
    if (n == 0) L_INFO("the boxaa is empty\n", procName);

    if ((baa = boxaaCreate(n)) == NULL)
        return (BOXAA *)ERROR_PTR("boxaa not made", procName, NULL);
    for (i = 0; i < n; i++) {
        if (fscanf(fp, "\nBoxa[%d] extent: x = %d, y = %d, w = %d, h = %d",
                   &ignore, &x, &y, &w, &h) != 5) {
            boxaaDestroy(&baa);
            return (BOXAA *)ERROR_PTR("boxa descr not valid", procName, NULL);
        }
        if ((boxa = boxaReadStream(fp)) == NULL) {
            boxaaDestroy(&baa);
            return (BOXAA *)ERROR_PTR("boxa not made", procName, NULL);
        }
        boxaaAddBoxa(baa, boxa, L_INSERT);
    }
    return baa;
}


/*!
 * \brief   boxaaReadMem()
 *
 * \param[in]    data     serialization of boxaa; in ascii
 * \param[in]    size     of data in bytes; can use strlen to get it
 * \return  baa, or NULL on error
 */
BOXAA *
boxaaReadMem(const l_uint8  *data,
             size_t          size)
{
FILE   *fp;
BOXAA  *baa;

    PROCNAME("boxaaReadMem");

    if (!data)
        return (BOXAA *)ERROR_PTR("data not defined", procName, NULL);
    if ((fp = fopenReadFromMemory(data, size)) == NULL)
        return (BOXAA *)ERROR_PTR("stream not opened", procName, NULL);

    baa = boxaaReadStream(fp);
    fclose(fp);
    if (!baa) L_ERROR("baa not read\n", procName);
    return baa;
}


/*!
 * \brief   boxaaWrite()
 *
 * \param[in]    filename
 * \param[in]    baa
 * \return  0 if OK, 1 on error
 */
l_ok
boxaaWrite(const char  *filename,
           BOXAA       *baa)
{
l_int32  ret;
FILE    *fp;

    PROCNAME("boxaaWrite");

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

    if ((fp = fopenWriteStream(filename, "w")) == NULL)
        return ERROR_INT("stream not opened", procName, 1);
    ret = boxaaWriteStream(fp, baa);
    fclose(fp);
    if (ret)
        return ERROR_INT("baa not written to stream", procName, 1);
    return 0;
}


/*!
 * \brief   boxaaWriteStream()
 *
 * \param[in]   fp    output file stream
 * \param[in]   baa
 * \return  0 if OK, 1 on error
 */
l_ok
boxaaWriteStream(FILE   *fp,
                 BOXAA  *baa)
{
l_int32  n, i, x, y, w, h;
BOX     *box;
BOXA    *boxa;

    PROCNAME("boxaaWriteStream");

    if (!fp)
        return ERROR_INT("stream not defined", procName, 1);
    if (!baa)
        return ERROR_INT("baa not defined", procName, 1);

    n = boxaaGetCount(baa);
    fprintf(fp, "\nBoxaa Version %d\n", BOXAA_VERSION_NUMBER);
    fprintf(fp, "Number of boxa = %d\n", n);

    for (i = 0; i < n; i++) {
        if ((boxa = boxaaGetBoxa(baa, i, L_CLONE)) == NULL)
            return ERROR_INT("boxa not found", procName, 1);
        boxaGetExtent(boxa, NULL, NULL, &box);
        boxGetGeometry(box, &x, &y, &w, &h);
        fprintf(fp, "\nBoxa[%d] extent: x = %d, y = %d, w = %d, h = %d",
                i, x, y, w, h);
        boxaWriteStream(fp, boxa);
        boxDestroy(&box);
        boxaDestroy(&boxa);
    }
    return 0;
}


/*!
 * \brief   boxaaWriteMem()
 *
 * \param[out]   pdata    data of serialized boxaa; ascii
 * \param[out]   psize    size of returned data
 * \param[in]    baa
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Serializes a boxaa in memory and puts the result in a buffer.
 * </pre>
 */
l_ok
boxaaWriteMem(l_uint8  **pdata,
              size_t    *psize,
              BOXAA     *baa)
{
l_int32  ret;
FILE    *fp;

    PROCNAME("boxaaWriteMem");

    if (pdata) *pdata = NULL;
    if (psize) *psize = 0;
    if (!pdata)
        return ERROR_INT("&data not defined", procName, 1);
    if (!psize)
        return ERROR_INT("&size not defined", procName, 1);
    if (!baa)
        return ERROR_INT("baa not defined", procName, 1);

#if HAVE_FMEMOPEN
    if ((fp = open_memstream((char **)pdata, psize)) == NULL)
        return ERROR_INT("stream not opened", procName, 1);
    ret = boxaaWriteStream(fp, baa);
#else
    L_INFO("work-around: writing to a temp file\n", procName);
  #ifdef _WIN32
    if ((fp = fopenWriteWinTempfile()) == NULL)
        return ERROR_INT("tmpfile stream not opened", procName, 1);
  #else
    if ((fp = tmpfile()) == NULL)
        return ERROR_INT("tmpfile stream not opened", procName, 1);
  #endif  /* _WIN32 */
    ret = boxaaWriteStream(fp, baa);
    rewind(fp);
    *pdata = l_binaryReadStream(fp, psize);
#endif  /* HAVE_FMEMOPEN */
    fclose(fp);
    return ret;
}


/*---------------------------------------------------------------------*
 *                         Boxa serialized I/O                         *
 *---------------------------------------------------------------------*/
/*!
 * \brief   boxaRead()
 *
 * \param[in]    filename
 * \return  boxa, or NULL on error
 */
BOXA *
boxaRead(const char  *filename)
{
FILE  *fp;
BOXA  *boxa;

    PROCNAME("boxaRead");

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

    if ((fp = fopenReadStream(filename)) == NULL)
        return (BOXA *)ERROR_PTR("stream not opened", procName, NULL);
    boxa = boxaReadStream(fp);
    fclose(fp);
    if (!boxa)
        return (BOXA *)ERROR_PTR("boxa not read", procName, NULL);
    return boxa;
}


/*!
 * \brief   boxaReadStream()
 *
 * \param[in]    fp   input file stream
 * \return  boxa, or NULL on error
 *
 * <pre>
 * Notes:
 *      (1) It is OK for the boxa to be empty (n == 0).
 * </pre>
 */
BOXA *
boxaReadStream(FILE  *fp)
{
l_int32  n, i, x, y, w, h, version;
l_int32  ignore;
BOX     *box;
BOXA    *boxa;

    PROCNAME("boxaReadStream");

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

    if (fscanf(fp, "\nBoxa Version %d\n", &version) != 1)
        return (BOXA *)ERROR_PTR("not a boxa file", procName, NULL);
    if (version != BOXA_VERSION_NUMBER)
        return (BOXA *)ERROR_PTR("invalid boxa version", procName, NULL);
    if (fscanf(fp, "Number of boxes = %d\n", &n) != 1)
        return (BOXA *)ERROR_PTR("not a boxa file", procName, NULL);
    if (n < 0)
        return (BOXA *)ERROR_PTR("num box ptrs < 0", procName, NULL);
    if (n > MaxBoxaPtrArraySize)
        return (BOXA *)ERROR_PTR("too many box ptrs", procName, NULL);
    if (n == 0) L_INFO("the boxa is empty\n", procName);

    if ((boxa = boxaCreate(n)) == NULL)
        return (BOXA *)ERROR_PTR("boxa not made", procName, NULL);
    for (i = 0; i < n; i++) {
        if (fscanf(fp, "  Box[%d]: x = %d, y = %d, w = %d, h = %d\n",
                &ignore, &x, &y, &w, &h) != 5) {
            boxaDestroy(&boxa);
            return (BOXA *)ERROR_PTR("box descr not valid", procName, NULL);
        }
        box = boxCreate(x, y, w, h);
        boxaAddBox(boxa, box, L_INSERT);
    }
    return boxa;
}


/*!
 * \brief   boxaReadMem()
 *
 * \param[in]    data    serialization of boxa; in ascii
 * \param[in]    size    of data in bytes; can use strlen to get it
 * \return  boxa, or NULL on error
 */
BOXA *
boxaReadMem(const l_uint8  *data,
            size_t          size)
{
FILE  *fp;
BOXA  *boxa;

    PROCNAME("boxaReadMem");

    if (!data)
        return (BOXA *)ERROR_PTR("data not defined", procName, NULL);
    if ((fp = fopenReadFromMemory(data, size)) == NULL)
        return (BOXA *)ERROR_PTR("stream not opened", procName, NULL);

    boxa = boxaReadStream(fp);
    fclose(fp);
    if (!boxa) L_ERROR("boxa not read\n", procName);
    return boxa;
}


/*!
 * \brief   boxaWriteDebug()
 *
 * \param[in]    filename
 * \param[in]    boxa
 * \return  0 if OK; 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Debug version, intended for use in the library when writing
 *          to files in a temp directory with names that are compiled in.
 *          This is used instead of boxaWrite() for all such library calls.
 *      (2) The global variable LeptDebugOK defaults to 0, and can be set
 *          or cleared by the function setLeptDebugOK().
 * </pre>
 */
l_ok
boxaWriteDebug(const char  *filename,
               BOXA        *boxa)
{
    PROCNAME("boxaWriteDebug");

    if (LeptDebugOK) {
        return boxaWrite(filename, boxa);
    } else {
        L_INFO("write to named temp file %s is disabled\n", procName, filename);
        return 0;
    }
}


/*!
 * \brief   boxaWrite()
 *
 * \param[in]    filename
 * \param[in]    boxa
 * \return  0 if OK, 1 on error
 */
l_ok
boxaWrite(const char  *filename,
          BOXA        *boxa)
{
l_int32  ret;
FILE    *fp;

    PROCNAME("boxaWrite");

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

    if ((fp = fopenWriteStream(filename, "w")) == NULL)
        return ERROR_INT("stream not opened", procName, 1);
    ret = boxaWriteStream(fp, boxa);
    fclose(fp);
    if (ret)
        return ERROR_INT("boxa not written to stream", procName, 1);

    return 0;
}


/*!
 * \brief   boxaWriteStream()
 *
 * \param[in]   fp     file stream; use NULL for stderr
 * \param[in]   boxa
 * \return  0 if OK, 1 on error
 */
l_ok
boxaWriteStream(FILE  *fp,
                BOXA  *boxa)
{
l_int32  n, i;
BOX     *box;

    PROCNAME("boxaWriteStream");

    if (!boxa)
        return ERROR_INT("boxa not defined", procName, 1);
    if (!fp)
        return boxaWriteStderr(boxa);

    n = boxaGetCount(boxa);
    fprintf(fp, "\nBoxa Version %d\n", BOXA_VERSION_NUMBER);
    fprintf(fp, "Number of boxes = %d\n", n);
    for (i = 0; i < n; i++) {
        if ((box = boxaGetBox(boxa, i, L_CLONE)) == NULL)
            return ERROR_INT("box not found", procName, 1);
        fprintf(fp, "  Box[%d]: x = %d, y = %d, w = %d, h = %d\n",
                i, box->x, box->y, box->w, box->h);
        boxDestroy(&box);
    }
    return 0;
}


/*!
 * \brief   boxaWriteStderr()
 *
 * \param[in]   boxa
 * \return  0 if OK, 1 on error
 */
l_ok
boxaWriteStderr(BOXA  *boxa)
{
l_int32  n, i;
BOX     *box;

    PROCNAME("boxaWriteStderr");

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

    n = boxaGetCount(boxa);
    lept_stderr("\nBoxa Version %d\n", BOXA_VERSION_NUMBER);
    lept_stderr("Number of boxes = %d\n", n);
    for (i = 0; i < n; i++) {
        if ((box = boxaGetBox(boxa, i, L_CLONE)) == NULL)
            return ERROR_INT("box not found", procName, 1);
        lept_stderr("  Box[%d]: x = %d, y = %d, w = %d, h = %d\n",
                i, box->x, box->y, box->w, box->h);
        boxDestroy(&box);
    }
    return 0;
}


/*!
 * \brief   boxaWriteMem()
 *
 * \param[out]   pdata   data of serialized boxa; ascii
 * \param[out]   psize   size of returned data
 * \param[in]    boxa
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) Serializes a boxa in memory and puts the result in a buffer.
 * </pre>
 */
l_ok
boxaWriteMem(l_uint8  **pdata,
             size_t    *psize,
             BOXA      *boxa)
{
l_int32  ret;
FILE    *fp;

    PROCNAME("boxaWriteMem");

    if (pdata) *pdata = NULL;
    if (psize) *psize = 0;
    if (!pdata)
        return ERROR_INT("&data not defined", procName, 1);
    if (!psize)
        return ERROR_INT("&size not defined", procName, 1);
    if (!boxa)
        return ERROR_INT("boxa not defined", procName, 1);

#if HAVE_FMEMOPEN
    if ((fp = open_memstream((char **)pdata, psize)) == NULL)
        return ERROR_INT("stream not opened", procName, 1);
    ret = boxaWriteStream(fp, boxa);
#else
    L_INFO("work-around: writing to a temp file\n", procName);
  #ifdef _WIN32
    if ((fp = fopenWriteWinTempfile()) == NULL)
        return ERROR_INT("tmpfile stream not opened", procName, 1);
  #else
    if ((fp = tmpfile()) == NULL)
        return ERROR_INT("tmpfile stream not opened", procName, 1);
  #endif  /* _WIN32 */
    ret = boxaWriteStream(fp, boxa);
    rewind(fp);
    *pdata = l_binaryReadStream(fp, psize);
#endif  /* HAVE_FMEMOPEN */
    fclose(fp);
    return ret;
}


/*---------------------------------------------------------------------*
 *                            Debug printing                           *
 *---------------------------------------------------------------------*/
/*!
 * \brief   boxPrintStreamInfo()
 *
 * \param[in]    fp    file stream; use NULL for stderr
 * \param[in]    box
 * \return  0 if OK, 1 on error
 *
 * <pre>
 * Notes:
 *      (1) This outputs debug info.  Use serialization functions to
 *          write to file if you want to read the data back.
 * </pre>
 */
l_ok
boxPrintStreamInfo(FILE  *fp,
                   BOX   *box)
{
    PROCNAME("boxPrintStreamInfo");

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

    if (!fp) {  /* output to stderr */
        lept_stderr(" Box: x = %d, y = %d, w = %d, h = %d\n",
                    box->x, box->y, box->w, box->h);
    } else {
        fprintf(fp, " Box: x = %d, y = %d, w = %d, h = %d\n",
                box->x, box->y, box->w, box->h);
    }
    return 0;
}