File: adaptmatch.cpp

package info (click to toggle)
tesseract 2.04-2%2Bsqueeze1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 7,336 kB
  • ctags: 6,860
  • sloc: cpp: 81,388; sh: 3,446; java: 1,220; makefile: 376
file content (2958 lines) | stat: -rwxr-xr-x 115,048 bytes parent folder | download
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
/******************************************************************************
 **                         Filename:    adaptmatch.c
 **                         Purpose:     High level adaptive matcher.
 **                         Author:      Dan Johnson
 **                         History:     Mon Mar 11 10:00:10 1991, DSJ, Created.
 **
 ** (c) Copyright Hewlett-Packard Company, 1988.
 ** Licensed under the Apache License, Version 2.0 (the "License");
 ** you may not use this file except in compliance with the License.
 ** You may obtain a copy of the License at
 ** http://www.apache.org/licenses/LICENSE-2.0
 ** Unless required by applicable law or agreed to in writing, software
 ** distributed under the License is distributed on an "AS IS" BASIS,
 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 ** See the License for the specific language governing permissions and
 ** limitations under the License.
 ******************************************************************************/

/**----------------------------------------------------------------------------
          Include Files and Type Defines
----------------------------------------------------------------------------**/
#include <ctype.h>
#include "adaptmatch.h"
#include "normfeat.h"
#include "mfoutline.h"
#include "picofeat.h"
#include "float2int.h"
#include "outfeat.h"
#include "emalloc.h"
#include "intfx.h"
#include "permnum.h"
#include "speckle.h"
#include "efio.h"
#include "normmatch.h"
#include "stopper.h"
#include "permute.h"
#include "context.h"
#include "ndminx.h"
#include "intproto.h"
#include "const.h"
#include "globals.h"
#include "werd.h"
#include "callcpp.h"
#include "tordvars.h"

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#include <math.h>
#ifdef __UNIX__
#include <assert.h>
#endif

#define ADAPT_TEMPLATE_SUFFIX ".a"
#define BUILT_IN_TEMPLATES_FILE "inttemp"
#define BUILT_IN_CUTOFFS_FILE "pffmtable"

#define MAX_MATCHES         10
#define UNLIKELY_NUM_FEAT 200
#define NO_DEBUG      0
#define MAX_ADAPTABLE_WERD_SIZE 40

#define ADAPTABLE_WERD    (GOOD_NUMBER + 0.05)

#define Y_DIM_OFFSET    (Y_SHIFT - BASELINE_Y_SHIFT)

#define WORST_POSSIBLE_RATING (1.0)

typedef struct
{
  inT32 BlobLength;
  int NumMatches;
  CLASS_ID Classes[MAX_NUM_CLASSES];
  FLOAT32 Ratings[MAX_CLASS_ID + 1];
  uinT8 Configs[MAX_CLASS_ID + 1];
  FLOAT32 BestRating;
  CLASS_ID BestClass;
  uinT8 BestConfig;
  CLASS_PRUNER_RESULTS CPResults;
}


ADAPT_RESULTS;

typedef struct
{
  ADAPT_TEMPLATES Templates;
  CLASS_ID ClassId;
  int ConfigId;
}


PROTO_KEY;

/**----------------------------------------------------------------------------
          Private Macros
----------------------------------------------------------------------------**/
#define MarginalMatch(Rating)       \
((Rating) > GreatAdaptiveMatch)

#define TempConfigReliable(Config)  \
((Config)->NumTimesSeen >= ReliableConfigThreshold)

#define InitIntFX() (FeaturesHaveBeenExtracted = FALSE)

/**----------------------------------------------------------------------------
          Private Function Prototypes
----------------------------------------------------------------------------**/
void AdaptToChar(TBLOB *Blob,
                 LINE_STATS *LineStats,
                 CLASS_ID ClassId,
                 FLOAT32 Threshold);

void AdaptToPunc(TBLOB *Blob,
                 LINE_STATS *LineStats,
                 CLASS_ID ClassId,
                 FLOAT32 Threshold);

void AddNewResult(ADAPT_RESULTS *Results,
                  CLASS_ID ClassId,
                  FLOAT32 Rating,
                  int ConfigId);

void AmbigClassifier(TBLOB *Blob,
                     LINE_STATS *LineStats,
                     INT_TEMPLATES Templates,
                     UNICHAR_ID *Ambiguities,
                     ADAPT_RESULTS *Results);

UNICHAR_ID *BaselineClassifier(TBLOB *Blob,
                               LINE_STATS *LineStats,
                               ADAPT_TEMPLATES Templates,
                               ADAPT_RESULTS *Results);

void make_config_pruner(INT_TEMPLATES templates, CONFIG_PRUNER *config_pruner);

void CharNormClassifier(TBLOB *Blob,
                        LINE_STATS *LineStats,
                        INT_TEMPLATES Templates,
                        ADAPT_RESULTS *Results);

void ClassifyAsNoise(TBLOB *Blob,
                     LINE_STATS *LineStats,
                     ADAPT_RESULTS *Results);

int CompareCurrentRatings(const void *arg1,
                          const void *arg2);

LIST ConvertMatchesToChoices(ADAPT_RESULTS *Results);

void DebugAdaptiveClassifier(TBLOB *Blob,
                             LINE_STATS *LineStats,
                             ADAPT_RESULTS *Results);

void DoAdaptiveMatch(TBLOB *Blob,
                     LINE_STATS *LineStats,
                     ADAPT_RESULTS *Results);

void GetAdaptThresholds(TWERD * Word,
LINE_STATS * LineStats,
const WERD_CHOICE& BestChoice,
const WERD_CHOICE& BestRawChoice, FLOAT32 Thresholds[]);

UNICHAR_ID *GetAmbiguities(TBLOB *Blob,
                           LINE_STATS *LineStats,
                           CLASS_ID CorrectClass);

int GetBaselineFeatures(TBLOB *Blob,
                        LINE_STATS *LineStats,
                        INT_TEMPLATES Templates,
                        INT_FEATURE_ARRAY IntFeatures,
                        CLASS_NORMALIZATION_ARRAY CharNormArray,
                        inT32 *BlobLength);

FLOAT32 GetBestRatingFor(TBLOB *Blob, LINE_STATS *LineStats, CLASS_ID ClassId);

int GetCharNormFeatures(TBLOB *Blob,
                        LINE_STATS *LineStats,
                        INT_TEMPLATES Templates,
                        INT_FEATURE_ARRAY IntFeatures,
                        CLASS_NORMALIZATION_ARRAY CharNormArray,
                        inT32 *BlobLength);

int GetIntBaselineFeatures(TBLOB *Blob,
                           LINE_STATS *LineStats,
                           INT_TEMPLATES Templates,
                           INT_FEATURE_ARRAY IntFeatures,
                           CLASS_NORMALIZATION_ARRAY CharNormArray,
                           inT32 *BlobLength);

int GetIntCharNormFeatures(TBLOB *Blob,
                           LINE_STATS *LineStats,
                           INT_TEMPLATES Templates,
                           INT_FEATURE_ARRAY IntFeatures,
                           CLASS_NORMALIZATION_ARRAY CharNormArray,
                           inT32 *BlobLength);

void InitMatcherRatings(register FLOAT32 *Rating);

int MakeNewTemporaryConfig(ADAPT_TEMPLATES Templates,
                           CLASS_ID ClassId,
                           int NumFeatures,
                           INT_FEATURE_ARRAY Features,
                           FEATURE_SET FloatFeatures);

PROTO_ID MakeNewTempProtos(FEATURE_SET Features,
int NumBadFeat,
FEATURE_ID BadFeat[],
INT_CLASS IClass,
ADAPT_CLASS Class, BIT_VECTOR TempProtoMask);

void MakePermanent(ADAPT_TEMPLATES Templates,
                   CLASS_ID ClassId,
                   int ConfigId,
                   TBLOB *Blob,
                   LINE_STATS *LineStats);

int MakeTempProtoPerm(void *item1, void *item2);

int NumBlobsIn(TWERD *Word);

int NumOutlinesInBlob(TBLOB *Blob);

void PrintAdaptiveMatchResults(FILE *File, ADAPT_RESULTS *Results);

void RemoveBadMatches(ADAPT_RESULTS *Results);

void RemoveExtraPuncs(ADAPT_RESULTS *Results);

void SetAdaptiveThreshold(FLOAT32 Threshold);
void ShowBestMatchFor(TBLOB *Blob,
                      LINE_STATS *LineStats,
                      CLASS_ID ClassId,
                      BOOL8 AdaptiveOn,
                      BOOL8 PreTrainedOn);


/**----------------------------------------------------------------------------
        Global Data Definitions and Declarations
----------------------------------------------------------------------------**/
/* name of current image file being processed */
extern char imagefile[];
INT_VAR(tessedit_single_match, FALSE, "Top choice only from CP");

/* variables used to hold performance statistics */
static int AdaptiveMatcherCalls = 0;
static int BaselineClassifierCalls = 0;
static int CharNormClassifierCalls = 0;
static int AmbigClassifierCalls = 0;
static int NumWordsAdaptedTo = 0;
static int NumCharsAdaptedTo = 0;
static int NumBaselineClassesTried = 0;
static int NumCharNormClassesTried = 0;
static int NumAmbigClassesTried = 0;
static int NumClassesOutput = 0;
static int NumAdaptationsFailed = 0;

/* define globals used to hold onto extracted features.  This is used
to map from the old scheme in which baseline features and char norm
features are extracted separately, to the new scheme in which they
are extracted at the same time. */
static BOOL8 FeaturesHaveBeenExtracted = FALSE;
static BOOL8 FeaturesOK = TRUE;
static INT_FEATURE_ARRAY BaselineFeatures;
static INT_FEATURE_ARRAY CharNormFeatures;
static INT_FX_RESULT_STRUCT FXInfo;

/* use a global variable to hold onto the current ratings so that the
comparison function passes to qsort can get at them */
static FLOAT32 *CurrentRatings;

/* define globals to hold filenames of training data */
static const char *BuiltInTemplatesFile = BUILT_IN_TEMPLATES_FILE;
static const char *BuiltInCutoffsFile = BUILT_IN_CUTOFFS_FILE;
static CLASS_CUTOFF_ARRAY CharNormCutoffs;
static CLASS_CUTOFF_ARRAY BaselineCutoffs;

/* use global variables to hold onto built-in templates and adapted
templates */
static INT_TEMPLATES PreTrainedTemplates;
static ADAPT_TEMPLATES AdaptedTemplates;

/* create dummy proto and config masks for use with the built-in templates */
static BIT_VECTOR AllProtosOn;
static BIT_VECTOR PrunedProtos;
static BIT_VECTOR AllConfigsOn;
static BIT_VECTOR AllProtosOff;
static BIT_VECTOR AllConfigsOff;
static BIT_VECTOR TempProtoMask;

/* define control knobs for adaptive matcher */
make_toggle_const(EnableAdaptiveMatcher, 1, MakeEnableAdaptiveMatcher);
/* PREV DEFAULT 0 */

make_toggle_const(UsePreAdaptedTemplates, 0, MakeUsePreAdaptedTemplates);
make_toggle_const(SaveAdaptedTemplates, 0, MakeSaveAdaptedTemplates);

make_toggle_var(EnableAdaptiveDebugger, 0, MakeEnableAdaptiveDebugger,
18, 1, SetEnableAdaptiveDebugger, "Enable match debugger");

make_int_var(MatcherDebugLevel, 0, MakeMatcherDebugLevel,
18, 2, SetMatcherDebugLevel, "Matcher Debug Level: ");

make_int_var(MatchDebugFlags, 0, MakeMatchDebugFlags,
18, 3, SetMatchDebugFlags, "Matcher Debug Flags: ");

make_toggle_var(EnableLearning, 1, MakeEnableLearning,
18, 4, SetEnableLearning, "Enable learning");
/* PREV DEFAULT 0 */
                                 /*record it for multiple pages */
static int old_enable_learning = 1;

make_int_var(LearningDebugLevel, 0, MakeLearningDebugLevel,
18, 5, SetLearningDebugLevel, "Learning Debug Level: ");

make_float_var(GoodAdaptiveMatch, 0.125, MakeGoodAdaptiveMatch,
18, 6, SetGoodAdaptiveMatch, "Good Match    (0-1): ");

make_float_var(GreatAdaptiveMatch, 0.0, MakeGreatAdaptiveMatch,
18, 7, SetGreatAdaptiveMatch, "Great Match   (0-1): ");
/* PREV DEFAULT 0.10 */

make_float_var(PerfectRating, 0.02, MakePerfectRating,
18, 8, SetPerfectRating, "Perfect Match (0-1): ");

make_float_var(BadMatchPad, 0.15, MakeBadMatchPad,
18, 9, SetBadMatchPad, "Bad Match Pad (0-1): ");

make_float_var(RatingMargin, 0.1, MakeRatingMargin,
18, 10, SetRatingMargin, "New template margin (0-1): ");

make_float_var(NoiseBlobLength, 12.0, MakeNoiseBlobLength,
18, 11, SetNoiseBlobLength, "Avg. noise blob length: ");

make_int_var(MinNumPermClasses, 1, MakeMinNumPermClasses,
18, 12, SetMinNumPermClasses, "Min # of permanent classes: ");
/* PREV DEFAULT 200 */

make_int_var(ReliableConfigThreshold, 2, MakeReliableConfigThreshold,
18, 13, SetReliableConfigThreshold,
"Reliable Config Threshold: ");

make_float_var(MaxAngleDelta, 0.015, MakeMaxAngleDelta,
18, 14, SetMaxAngleDelta,
"Maximum angle delta for proto clustering: ");

make_toggle_var(EnableIntFX, 1, MakeEnableIntFX,
18, 15, SetEnableIntFX, "Enable integer fx");
/* PREV DEFAULT 0 */

make_toggle_var(EnableNewAdaptRules, 1, MakeEnableNewAdaptRules,
18, 16, SetEnableNewAdaptRules,
"Enable new adaptation rules");
/* PREV DEFAULT 0 */

make_float_var(RatingScale, 1.5, MakeRatingScale,
18, 17, SetRatingScale, "Rating scale: ");

make_float_var(CertaintyScale, 20.0, MakeCertaintyScale,
18, 18, SetCertaintyScale, "CertaintyScale: ");

make_int_var(FailedAdaptionsBeforeReset, 150, MakeFailedAdaptionsBeforeReset,
18, 19, SetFailedAdaptionsBeforeReset,
"Number of failed adaptions before adapted templates reset: ");
double_VAR(tessedit_class_miss_scale, 0.00390625,
           "Scale factor for features not used");

int tess_cn_matching = 0;
int tess_bn_matching = 0;

/**----------------------------------------------------------------------------
              Public Code
----------------------------------------------------------------------------**/
/*---------------------------------------------------------------------------*/
LIST AdaptiveClassifier(TBLOB *Blob, TBLOB *DotBlob, TEXTROW *Row) {
/*
 **                         Parameters:
 **              Blob            blob to be classified
 **              DotBlob         (obsolete)
 **              Row             row of text that word appears in
 **                         Globals:
 **                         CurrentRatings
              used by compare function for qsort
**                          Operation: This routine calls the adaptive matcher which returns
**      (in an array) the class id of each class matched.  It also
**                          returns the number of classes matched.
**                          For each class matched it places the best rating
**                          found for that class into the Ratings array.
**                          Bad matches are then removed so that they don't need to be
**                          sorted.  The remaining good matches are then sorted and
**                          converted to choices.
**                          This routine also performs some simple speckle filtering.
**                          Return: List of choices found by adaptive matcher.
**                          Exceptions: none
**                          History: Mon Mar 11 10:00:58 1991, DSJ, Created.
*/
  LIST Choices;
  ADAPT_RESULTS* Results = new ADAPT_RESULTS;
  LINE_STATS LineStats;

  if (FailedAdaptionsBeforeReset >= 0 &&
      NumAdaptationsFailed >= FailedAdaptionsBeforeReset) {
    NumAdaptationsFailed = 0;
    ResetAdaptiveClassifier();
  }
  if (AdaptedTemplates == NULL)
    AdaptedTemplates = NewAdaptedTemplates ();
  EnterClassifyMode;

  Results->BlobLength = MAX_INT32;
  Results->NumMatches = 0;
  Results->BestRating = WORST_POSSIBLE_RATING;
  Results->BestClass = NO_CLASS;
  Results->BestConfig = 0;
  GetLineStatsFromRow(Row, &LineStats);
  InitMatcherRatings (Results->Ratings);

  DoAdaptiveMatch(Blob, &LineStats, Results);
  RemoveBadMatches(Results);

  /* save ratings in a global so that CompareCurrentRatings() can see them */
  CurrentRatings = Results->Ratings;
  qsort((void*) (Results->Classes), Results->NumMatches,
    sizeof (CLASS_ID), CompareCurrentRatings);
  RemoveExtraPuncs(Results);
  Choices = ConvertMatchesToChoices(Results);

  if (MatcherDebugLevel >= 1) {
    cprintf ("AD Matches =  ");
    PrintAdaptiveMatchResults(stdout, Results);
  }

  if (LargeSpeckle (Blob, Row))
    Choices = AddLargeSpeckleTo (Choices);

#ifndef GRAPHICS_DISABLED
  if (EnableAdaptiveDebugger)
    DebugAdaptiveClassifier(Blob, &LineStats, Results);
#endif

  NumClassesOutput += count (Choices);
  if (Choices == NIL) {
    char empty_lengths[] = {0};
    if (!bln_numericmode)
      tprintf ("Nil classification!\n");  // Should never normally happen.
    return (append_choice (NIL, "", empty_lengths, 50.0f, -20.0f, -1));
  }

  delete Results;
  return Choices;
}                                /* AdaptiveClassifier */


/*---------------------------------------------------------------------------*/
void AdaptToWord(TWERD *Word,
                 TEXTROW *Row,
                 const WERD_CHOICE& BestChoice,
                 const WERD_CHOICE& BestRawChoice,
                 const char *rejmap) {
/*
 **                         Parameters:
 **                         Word
              word to be adapted to
**                          Row
              row of text that word is found in
**                          BestChoice
              best choice for word found by system
**                          BestRawChoice
              best choice for word found by classifier only
**                          Globals:
**                          EnableLearning
              TRUE if learning is enabled
**                          Operation: This routine implements a preliminary version of the
**                          rules which are used to decide which characters to adapt to.
**                          A word is adapted to if it is in the dictionary or if it
**                          is a "good" number (no trailing units, etc.).  It cannot
**                          contain broken or merged characters.  Within that word, only
**                          letters and digits are adapted to (no punctuation).
**                          Return: none
**                          Exceptions: none
**                          History: Thu Mar 14 07:40:36 1991, DSJ, Created.
*/
  TBLOB *Blob;
  LINE_STATS LineStats;
  FLOAT32 Thresholds[MAX_ADAPTABLE_WERD_SIZE];
  FLOAT32 *Threshold;
  const char *map = rejmap;
  char map_char = '1';
  const char* BestChoice_string = BestChoice.string().string();
  const char* BestChoice_lengths = BestChoice.lengths().string();

  if (strlen(BestChoice_lengths) > MAX_ADAPTABLE_WERD_SIZE)
    return;

  if (EnableLearning) {
    NumWordsAdaptedTo++;

    #ifndef SECURE_NAMES
    if (LearningDebugLevel >= 1)
      cprintf ("\n\nAdapting to word = %s\n", BestChoice.string().string());
    #endif
    GetLineStatsFromRow(Row, &LineStats);

    GetAdaptThresholds(Word,
                       &LineStats,
                       BestChoice,
                       BestRawChoice,
                       Thresholds);

    for (Blob = Word->blobs, Threshold = Thresholds; Blob != NULL;
         Blob = Blob->next, BestChoice_string += *(BestChoice_lengths++),
             Threshold++) {
      InitIntFX();

      if (rejmap != NULL)
        map_char = *map++;

      assert (map_char == '1' || map_char == '0');

      if (map_char == '1') {

//        if (unicharset.get_isalpha (BestChoice_string, *BestChoice_lengths) ||
//            unicharset.get_isdigit (BestChoice_string, *BestChoice_lengths)) {
          /* SPECIAL RULE:  don't adapt to an 'i' which is the first char
             in a word because they are too ambiguous with 'I'.
             The new adaptation rules should account for this
             automatically, since they exclude ambiguous words from
             adaptation, but for safety's sake we'll leave the rule in.
             Also, don't adapt to i's that have only 1 blob in them
             because this creates too much ambiguity for broken
             characters. */
          if (*BestChoice_lengths == 1 &&
              (*BestChoice_string == 'i'
               || (il1_adaption_test && *BestChoice_string == 'I' &&
               (Blob->next == NULL ||
               unicharset.get_islower (BestChoice_string + *BestChoice_lengths,
                                       *(BestChoice_lengths + 1)))))
              && (Blob == Word->blobs
                  || (!(unicharset.get_isalpha (BestChoice_string -
                                                *(BestChoice_lengths - 1),
                                                *(BestChoice_lengths - 1)) ||
                        unicharset.get_isdigit (BestChoice_string -
                                                *(BestChoice_lengths - 1),
                                                *(BestChoice_lengths - 1))))

                  || (!il1_adaption_test && NumOutlinesInBlob(Blob) != 2))) {
            if (LearningDebugLevel >= 1)
              cprintf ("Rejecting char = %s\n", unicharset.id_to_unichar(
                           unicharset.unichar_to_id(BestChoice_string,
                                                    *BestChoice_lengths)));
          }
          else {
            #ifndef SECURE_NAMES
            if (LearningDebugLevel >= 1)
              cprintf ("Adapting to char = %s, thr= %g\n",
                       unicharset.id_to_unichar(
                           unicharset.unichar_to_id(BestChoice_string,
                                                    *BestChoice_lengths)),
                           *Threshold);
            #endif
            AdaptToChar(Blob, &LineStats,
                        unicharset.unichar_to_id(BestChoice_string,
                                                 *BestChoice_lengths),
                        *Threshold);
          }
//        }
//        else
//          AdaptToPunc(Blob, &LineStats,
//                      unicharset.unichar_to_id(BestChoice_string,
//                                               *BestChoice_lengths),
//                      *Threshold);
      }
    }
    if (LearningDebugLevel >= 1)
      cprintf ("\n");
  }
}                                /* AdaptToWord */


/*---------------------------------------------------------------------------*/
void EndAdaptiveClassifier() {
/*
 **                         Parameters: none
 **                         Globals:
 **                         AdaptedTemplates
              current set of adapted templates
**                          SaveAdaptedTemplates
              TRUE if templates should be saved
**                          EnableAdaptiveMatcher
              TRUE if adaptive matcher is enabled
**                          Operation: This routine performs cleanup operations on the
**                          adaptive classifier.  It should be called before the
**                          program is terminated.  Its main function is to save
**                          the adapted templates to a file.
**                          Return: none
**                          Exceptions: none
**                          History: Tue Mar 19 14:37:06 1991, DSJ, Created.
*/
  char Filename[256];
  FILE *File;

  #ifndef SECURE_NAMES
  if (EnableAdaptiveMatcher && SaveAdaptedTemplates) {
    strcpy(Filename, imagefile);
    strcat(Filename, ADAPT_TEMPLATE_SUFFIX);
    File = fopen (Filename, "wb");
    if (File == NULL)
      cprintf ("Unable to save adapted templates to %s!\n", Filename);
    else {
      cprintf ("\nSaving adapted templates to %s ...", Filename);
      fflush(stdout);
      WriteAdaptedTemplates(File, AdaptedTemplates);
      cprintf ("\n");
      fclose(File);
    }
  }
  #endif
  if (PreTrainedTemplates == NULL)
    return;  // This function isn't safe to run twice.
  EndDangerousAmbigs();
  FreeNormProtos();
  free_int_templates(PreTrainedTemplates);
  PreTrainedTemplates = NULL;
  FreeBitVector(AllProtosOn);
  FreeBitVector(PrunedProtos);
  FreeBitVector(AllConfigsOn);
  FreeBitVector(AllProtosOff);
  FreeBitVector(AllConfigsOff);
  FreeBitVector(TempProtoMask);
  AllProtosOn = NULL;
  PrunedProtos = NULL;
  AllConfigsOn = NULL;
  AllProtosOff = NULL;
  AllConfigsOff = NULL;
  TempProtoMask = NULL;
}                                /* EndAdaptiveClassifier */


/*---------------------------------------------------------------------------*/
void InitAdaptiveClassifier() {
/*
 **                         Parameters: none
 **                         Globals:
 **                         BuiltInTemplatesFile
              file to get built-in temps from
**                          BuiltInCutoffsFile
              file to get avg. feat per class from
**                          PreTrainedTemplates
              pre-trained configs and protos
**                          AdaptedTemplates
              templates adapted to current page
**                          CharNormCutoffs
              avg # of features per class
**                          AllProtosOn
              dummy proto mask with all bits 1
**                          AllConfigsOn
              dummy config mask with all bits 1
**                          UsePreAdaptedTemplates
              enables use of pre-adapted templates
**                          Operation: This routine reads in the training information needed
**                          by the adaptive classifier and saves it into global
**                          variables.
**                          Return: none
**                          Exceptions: none
**                          History: Mon Mar 11 12:49:34 1991, DSJ, Created.
*/
  int i;
  FILE *File;
  STRING Filename;

  if (!EnableAdaptiveMatcher)
    return;
  if (PreTrainedTemplates != NULL)
    EndAdaptiveClassifier();  // Don't leak with multiple inits.

  Filename = language_data_path_prefix;
  Filename += BuiltInTemplatesFile;
  #ifndef SECURE_NAMES
  //      cprintf( "\nReading built-in templates from %s ...",
  //              Filename);
  fflush(stdout);
  #endif

  #ifdef __UNIX__
  File = Efopen (Filename.string(), "r");
  #else
  File = Efopen (Filename.string(), "rb");
  #endif
  PreTrainedTemplates = ReadIntTemplates (File, TRUE);
  fclose(File);

  Filename = language_data_path_prefix;
  Filename += BuiltInCutoffsFile;
  #ifndef SECURE_NAMES
  //      cprintf( "\nReading built-in pico-feature cutoffs from %s ...",
  //              Filename);
  fflush(stdout);
  #endif
  ReadNewCutoffs (Filename.string(), PreTrainedTemplates->IndexFor,
                  CharNormCutoffs);

  GetNormProtos();

  InitIntegerMatcher();
  InitIntegerFX();

  AllProtosOn = NewBitVector(MAX_NUM_PROTOS);
  PrunedProtos = NewBitVector(MAX_NUM_PROTOS);
  AllConfigsOn = NewBitVector(MAX_NUM_CONFIGS);
  AllProtosOff = NewBitVector(MAX_NUM_PROTOS);
  AllConfigsOff = NewBitVector(MAX_NUM_CONFIGS);
  TempProtoMask = NewBitVector(MAX_NUM_PROTOS);
  set_all_bits(AllProtosOn, WordsInVectorOfSize(MAX_NUM_PROTOS));
  set_all_bits(PrunedProtos, WordsInVectorOfSize(MAX_NUM_PROTOS));
  set_all_bits(AllConfigsOn, WordsInVectorOfSize(MAX_NUM_CONFIGS));
  zero_all_bits(AllProtosOff, WordsInVectorOfSize(MAX_NUM_PROTOS));
  zero_all_bits(AllConfigsOff, WordsInVectorOfSize(MAX_NUM_CONFIGS));

  if (UsePreAdaptedTemplates) {
    Filename = imagefile;
    Filename += ADAPT_TEMPLATE_SUFFIX;
    File = fopen (Filename.string(), "rb");
    if (File == NULL)
      AdaptedTemplates = NewAdaptedTemplates ();
    else {
      #ifndef SECURE_NAMES
      cprintf ("\nReading pre-adapted templates from %s ...", Filename.string());
      fflush(stdout);
      #endif
      AdaptedTemplates = ReadAdaptedTemplates (File);
      cprintf ("\n");
      fclose(File);
      PrintAdaptedTemplates(stdout, AdaptedTemplates);

      for (i = 0; i < (AdaptedTemplates->Templates)->NumClasses; i++) {
        BaselineCutoffs[i] =
          CharNormCutoffs[PreTrainedTemplates->IndexFor[
          AdaptedTemplates->Templates->ClassIdFor[i]]];
      }
    }
  } else {
    if (AdaptedTemplates != NULL)
      free_adapted_templates(AdaptedTemplates);
    AdaptedTemplates = NewAdaptedTemplates ();
  }
  old_enable_learning = EnableLearning;

}                                /* InitAdaptiveClassifier */

void ResetAdaptiveClassifier() {
  free_adapted_templates(AdaptedTemplates);
  AdaptedTemplates = NULL;
}


/*---------------------------------------------------------------------------*/
void InitAdaptiveClassifierVars() {
/*
 **                         Parameters: none
 **                         Globals: none
 **                         Operation: This routine installs the control knobs used by the
 **                         adaptive matcher.
 **                         Return: none
 **                         Exceptions: none
 **                         History: Mon Mar 11 12:49:34 1991, DSJ, Created.
 */
  VALUE dummy;

  string_variable (BuiltInTemplatesFile, "BuiltInTemplatesFile",
    BUILT_IN_TEMPLATES_FILE);
  string_variable (BuiltInCutoffsFile, "BuiltInCutoffsFile",
    BUILT_IN_CUTOFFS_FILE);

  MakeEnableAdaptiveMatcher();
  MakeUsePreAdaptedTemplates();
  MakeSaveAdaptedTemplates();

  MakeEnableLearning();
  MakeEnableAdaptiveDebugger();
  MakeBadMatchPad();
  MakeGoodAdaptiveMatch();
  MakeGreatAdaptiveMatch();
  MakeNoiseBlobLength();
  MakeMinNumPermClasses();
  MakeReliableConfigThreshold();
  MakeMaxAngleDelta();
  MakeLearningDebugLevel();
  MakeMatcherDebugLevel();
  MakeMatchDebugFlags();
  MakeRatingMargin();
  MakePerfectRating();
  MakeEnableIntFX();
  MakeEnableNewAdaptRules();
  MakeRatingScale();
  MakeCertaintyScale();
  MakeFailedAdaptionsBeforeReset();

  InitPicoFXVars();
  InitOutlineFXVars();  //?

}                                /* InitAdaptiveClassifierVars */


/*---------------------------------------------------------------------------*/
void PrintAdaptiveStatistics(FILE *File) {
/*
 **                         Parameters:
 **                         File
              open text file to print adaptive statistics to
**                          Globals: none
**                          Operation: Print to File the statistics which have been gathered
**                          for the adaptive matcher.
**                          Return: none
**                          Exceptions: none
**                          History: Thu Apr 18 14:37:37 1991, DSJ, Created.
*/
  #ifndef SECURE_NAMES

  fprintf (File, "\nADAPTIVE MATCHER STATISTICS:\n");
  fprintf (File, "\tNum blobs classified = %d\n", AdaptiveMatcherCalls);
  fprintf (File, "\tNum classes output   = %d (Avg = %4.2f)\n",
    NumClassesOutput,
    ((AdaptiveMatcherCalls == 0) ? (0.0) :
  ((float) NumClassesOutput / AdaptiveMatcherCalls)));
  fprintf (File, "\t\tBaseline Classifier: %4d calls (%4.2f classes/call)\n",
    BaselineClassifierCalls,
    ((BaselineClassifierCalls == 0) ? (0.0) :
  ((float) NumBaselineClassesTried / BaselineClassifierCalls)));
  fprintf (File, "\t\tCharNorm Classifier: %4d calls (%4.2f classes/call)\n",
    CharNormClassifierCalls,
    ((CharNormClassifierCalls == 0) ? (0.0) :
  ((float) NumCharNormClassesTried / CharNormClassifierCalls)));
  fprintf (File, "\t\tAmbig    Classifier: %4d calls (%4.2f classes/call)\n",
    AmbigClassifierCalls,
    ((AmbigClassifierCalls == 0) ? (0.0) :
  ((float) NumAmbigClassesTried / AmbigClassifierCalls)));

  fprintf (File, "\nADAPTIVE LEARNER STATISTICS:\n");
  fprintf (File, "\tNumber of words adapted to: %d\n", NumWordsAdaptedTo);
  fprintf (File, "\tNumber of chars adapted to: %d\n", NumCharsAdaptedTo);

  if (UsePreAdaptedTemplates)
    PrintAdaptedTemplates(File, AdaptedTemplates);
  #endif
}                                /* PrintAdaptiveStatistics */


/*---------------------------------------------------------------------------*/
void SettupPass1() {
/*
 **                         Parameters: none
 **                         Globals:
 **                         EnableLearning
              set to TRUE by this routine
**                          Operation: This routine prepares the adaptive matcher for the start
**                          of the first pass.  Learning is enabled (unless it is
**                          disabled for the whole program).
**                          Return: none
**                          Exceptions: none
**                          History: Mon Apr 15 16:39:29 1991, DSJ, Created.
*/
  /* Note: this is somewhat redundant, it simply says that if learning is
  enabled then it will remain enabled on the first pass.  If it is
  disabled, then it will remain disabled.  This is only put here to
  make it very clear that learning is controlled directly by the global
    setting of EnableLearning. */
  EnableLearning = old_enable_learning;

  SettupStopperPass1();

}                                /* SettupPass1 */


/*---------------------------------------------------------------------------*/
void SettupPass2() {
/*
 **                         Parameters: none
 **                         Globals:
 **                         EnableLearning
              set to FALSE by this routine
**                          Operation: This routine prepares the adaptive matcher for the start
**                          of the second pass.  Further learning is disabled.
**                          Return: none
**                          Exceptions: none
**                          History: Mon Apr 15 16:39:29 1991, DSJ, Created.
*/
  EnableLearning = FALSE;
  SettupStopperPass2();

}                                /* SettupPass2 */


/*---------------------------------------------------------------------------*/
void MakeNewAdaptedClass(TBLOB *Blob,
                         LINE_STATS *LineStats,
                         CLASS_ID ClassId,
                         ADAPT_TEMPLATES Templates) {
/*
 **                         Parameters:
 **                         Blob
              blob to model new class after
**                          LineStats
              statistics for text row blob is in
**                          ClassId
              id of new class to be created
**                          Templates
              adapted templates to add new class to
**                          Globals:
**                          AllProtosOn
              dummy mask with all 1's
**                          BaselineCutoffs
              kludge needed to get cutoffs
**                          PreTrainedTemplates
              kludge needed to get cutoffs
**                          Operation: This routine creates a new adapted class and uses Blob
**                          as the model for the first config in that class.
**                          Return: none
**                          Exceptions: none
**                          History: Thu Mar 14 12:49:39 1991, DSJ, Created.
*/
  FEATURE_SET Features;
  int Fid, Pid;
  FEATURE Feature;
  int NumFeatures;
  TEMP_PROTO TempProto;
  PROTO Proto;
  ADAPT_CLASS Class;
  INT_CLASS IClass;
  CLASS_INDEX ClassIndex;
  TEMP_CONFIG Config;

  NormMethod = baseline;
  Features = ExtractOutlineFeatures (Blob, LineStats);
  NumFeatures = Features->NumFeatures;
  if (NumFeatures > UNLIKELY_NUM_FEAT) {
    FreeFeatureSet(Features);
    return;
  }

  Class = NewAdaptedClass ();
  ClassIndex = AddAdaptedClass (Templates, Class, ClassId);
  Config = NewTempConfig (NumFeatures - 1);
  TempConfigFor (Class, 0) = Config;

  /* this is a kludge to construct cutoffs for adapted templates */
  if (Templates == AdaptedTemplates)
    BaselineCutoffs[ClassIndex] =
        CharNormCutoffs[PreTrainedTemplates->IndexFor[ClassId]];

  IClass = ClassForClassId (Templates->Templates, ClassId);

  for (Fid = 0; Fid < Features->NumFeatures; Fid++) {
    Pid = AddIntProto (IClass);
    assert (Pid != NO_PROTO);

    Feature = Features->Features[Fid];
    TempProto = NewTempProto ();
    Proto = &(TempProto->Proto);

    /* compute proto params - NOTE that Y_DIM_OFFSET must be used because
       ConvertProto assumes that the Y dimension varies from -0.5 to 0.5
       instead of the -0.25 to 0.75 used in baseline normalization */
    Proto->Angle = Feature->Params[OutlineFeatDir];
    Proto->X = Feature->Params[OutlineFeatX];
    Proto->Y = Feature->Params[OutlineFeatY] - Y_DIM_OFFSET;
    Proto->Length = Feature->Params[OutlineFeatLength];
    FillABC(Proto);

    TempProto->ProtoId = Pid;
    SET_BIT (Config->Protos, Pid);

    ConvertProto(Proto, Pid, IClass);
    AddProtoToProtoPruner(Proto, Pid, IClass);

    Class->TempProtos = push (Class->TempProtos, TempProto);
  }
  FreeFeatureSet(Features);

  AddIntConfig(IClass);
  ConvertConfig (AllProtosOn, 0, IClass);

  if (LearningDebugLevel >= 1) {
    cprintf ("Added new class '%s' with index %d and %d protos.\n",
             unicharset.id_to_unichar(ClassId), ClassIndex, NumFeatures);
  }
}                                /* MakeNewAdaptedClass */


/*---------------------------------------------------------------------------*/
int GetAdaptiveFeatures(TBLOB *Blob,
                        LINE_STATS *LineStats,
                        INT_FEATURE_ARRAY IntFeatures,
                        FEATURE_SET *FloatFeatures) {
/*
 **                         Parameters:
 **                         Blob
              blob to extract features from
**                          LineStats
              statistics about text row blob is in
**                          IntFeatures
              array to fill with integer features
**                          FloatFeatures
              place to return actual floating-pt features
**                          Globals: none
**                          Operation: This routine sets up the feature extractor to extract
**                          baseline normalized pico-features.
**                          The extracted pico-features are converted
**                          to integer form and placed in IntFeatures.  The original
**                          floating-pt. features are returned in FloatFeatures.
**                          Return: Number of pico-features returned (0 if an error occurred)
**                          Exceptions: none
**                          History: Tue Mar 12 17:55:18 1991, DSJ, Created.
*/
  FEATURE_SET Features;
  int NumFeatures;

  NormMethod = baseline;
  Features = ExtractPicoFeatures (Blob, LineStats);

  NumFeatures = Features->NumFeatures;
  if (NumFeatures > UNLIKELY_NUM_FEAT) {
    FreeFeatureSet(Features);
    return (0);
  }

  ComputeIntFeatures(Features, IntFeatures);
  *FloatFeatures = Features;

  return (NumFeatures);

}                                /* GetAdaptiveFeatures */


/**----------------------------------------------------------------------------
              Private Code
----------------------------------------------------------------------------**/
/*---------------------------------------------------------------------------*/
int AdaptableWord(TWERD *Word,
                  const char *BestChoice,
                  const char *BestChoice_lengths,
                  const char *BestRawChoice,
                  const char *BestRawChoice_lengths) {
/*
 **                         Parameters:
 **                         Word
              current word
**                          BestChoice
              best overall choice for word with context
**                          BestRawChoice
              best choice for word without context
**                          Globals: none
**                          Operation: Return TRUE if the specified word is acceptable for
**                          adaptation.
**                          Return: TRUE or FALSE
**                          Exceptions: none
**                          History: Thu May 30 14:25:06 1991, DSJ, Created.
*/
  int BestChoiceLength;

  return (                       /* rules that apply in general - simplest to compute first */
  /*        EnableLearning                                                && */
                                 /* new rules */
    BestChoice != NULL && BestRawChoice != NULL && Word != NULL &&
    (BestChoiceLength = strlen (BestChoice_lengths)) > 0 &&
    BestChoiceLength == NumBlobsIn (Word) &&
    BestChoiceLength <= MAX_ADAPTABLE_WERD_SIZE && (
    (EnableNewAdaptRules
    &&
    CurrentBestChoiceAdjustFactor
    ()
    <=
    ADAPTABLE_WERD
    &&
    AlternativeChoicesWorseThan
    (ADAPTABLE_WERD)
    &&
    CurrentBestChoiceIs
    (BestChoice, BestChoice_lengths))
    ||
                                 /* old rules */
    (!EnableNewAdaptRules
    &&
    BestChoiceLength
    ==
    strlen
    (BestRawChoice_lengths)
    &&
    ((valid_word (BestChoice) && case_ok (BestChoice, BestChoice_lengths)) || (valid_number (BestChoice, BestChoice_lengths) && pure_number (BestChoice, BestChoice_lengths))) && punctuation_ok (BestChoice, BestChoice_lengths) != -1 && punctuation_ok (BestChoice, BestChoice_lengths) <= 1)));

}                                /* AdaptableWord */


/*---------------------------------------------------------------------------*/
void AdaptToChar(TBLOB *Blob,
                 LINE_STATS *LineStats,
                 CLASS_ID ClassId,
                 FLOAT32 Threshold) {
/*
 **                         Parameters:
 **                         Blob
              blob to add to templates for ClassId
**                          LineStats
              statistics about text line blob is in
**                          ClassId
              class to add blob to
**                          Threshold
              minimum match rating to existing template
**                          Globals:
**                          AdaptedTemplates
              current set of adapted templates
**                          AllProtosOn
              dummy mask to match against all protos
**                          AllConfigsOn
              dummy mask to match against all configs
**                          Operation:
**                          Return: none
**                          Exceptions: none
**                          History: Thu Mar 14 09:36:03 1991, DSJ, Created.
*/
  int NumFeatures;
  INT_FEATURE_ARRAY IntFeatures;
  INT_RESULT_STRUCT IntResult;
  CLASS_INDEX ClassIndex;
  INT_CLASS IClass;
  ADAPT_CLASS Class;
  TEMP_CONFIG TempConfig;
  FEATURE_SET FloatFeatures;
  int NewTempConfigId;

  NumCharsAdaptedTo++;
  if (!LegalClassId (ClassId))
    return;

  if (UnusedClassIdIn (AdaptedTemplates->Templates, ClassId)) {
    MakeNewAdaptedClass(Blob, LineStats, ClassId, AdaptedTemplates);
  }
  else {
    IClass = ClassForClassId (AdaptedTemplates->Templates, ClassId);
    ClassIndex = AdaptedTemplates->Templates->IndexFor[ClassId];
    Class = AdaptedTemplates->Class[ClassIndex];

    NumFeatures = GetAdaptiveFeatures (Blob, LineStats,
      IntFeatures, &FloatFeatures);
    if (NumFeatures <= 0)
      return;

    SetBaseLineMatch();
    IntegerMatcher (IClass, AllProtosOn, AllConfigsOn,
      NumFeatures, NumFeatures, IntFeatures, 0,
      &IntResult, NO_DEBUG);

    SetAdaptiveThreshold(Threshold);

    if (IntResult.Rating <= Threshold) {
      if (ConfigIsPermanent (Class, IntResult.Config)) {
        if (LearningDebugLevel >= 1)
          cprintf ("Found good match to perm config %d = %4.1f%%.\n",
            IntResult.Config, (1.0 - IntResult.Rating) * 100.0);
        FreeFeatureSet(FloatFeatures);
        return;
      }

      TempConfig = TempConfigFor (Class, IntResult.Config);
      IncreaseConfidence(TempConfig);
      if (LearningDebugLevel >= 1)
        cprintf ("Increasing reliability of temp config %d to %d.\n",
          IntResult.Config, TempConfig->NumTimesSeen);

      if (TempConfigReliable (TempConfig))
        MakePermanent (AdaptedTemplates, ClassId, IntResult.Config,
          Blob, LineStats);
    }
    else {
      if (LearningDebugLevel >= 1)
        cprintf ("Found poor match to temp config %d = %4.1f%%.\n",
          IntResult.Config, (1.0 - IntResult.Rating) * 100.0);
      NewTempConfigId = MakeNewTemporaryConfig(AdaptedTemplates,
                                               ClassId,
                                               NumFeatures,
                                               IntFeatures,
                                               FloatFeatures);

      if (NewTempConfigId >= 0 &&
          TempConfigReliable (TempConfigFor (Class, NewTempConfigId)))
        MakePermanent (AdaptedTemplates, ClassId, NewTempConfigId,
                       Blob, LineStats);

#ifndef GRAPHICS_DISABLED
	  if (LearningDebugLevel >= 1) {
        IntegerMatcher (IClass, AllProtosOn, AllConfigsOn,
          NumFeatures, NumFeatures, IntFeatures, 0,
          &IntResult, NO_DEBUG);
        cprintf ("Best match to temp config %d = %4.1f%%.\n",
          IntResult.Config, (1.0 - IntResult.Rating) * 100.0);
        if (LearningDebugLevel >= 2) {
          uinT32 ConfigMask;
          ConfigMask = 1 << IntResult.Config;
          ShowMatchDisplay();
          IntegerMatcher (IClass, AllProtosOn, (BIT_VECTOR)&ConfigMask,
            NumFeatures, NumFeatures, IntFeatures, 0,
            &IntResult, 6 | 0x19);
          UpdateMatchDisplay();
          GetClassToDebug ("Adapting");
        }
      }
#endif  // GRAPHICS_DISABLED
    }
    FreeFeatureSet(FloatFeatures);
  }
}                                /* AdaptToChar */


/*---------------------------------------------------------------------------*/
void AdaptToPunc(TBLOB *Blob,
                 LINE_STATS *LineStats,
                 CLASS_ID ClassId,
                 FLOAT32 Threshold) {
/*
 **                         Parameters:
 **                         Blob
              blob to add to templates for ClassId
**                          LineStats
              statistics about text line blob is in
**                          ClassId
              class to add blob to
**                          Threshold
              minimum match rating to existing template
**                          Globals:
**                          PreTrainedTemplates
              current set of built-in templates
**                          Operation:
**                          Return: none
**                          Exceptions: none
**                          History: Thu Mar 14 09:36:03 1991, DSJ, Created.
*/
  ADAPT_RESULTS Results;
  int i;

  Results.BlobLength = MAX_INT32;
  Results.NumMatches = 0;
  Results.BestRating = WORST_POSSIBLE_RATING;
  Results.BestClass = NO_CLASS;
  Results.BestConfig = 0;
  InitMatcherRatings (Results.Ratings);
  CharNormClassifier(Blob, LineStats, PreTrainedTemplates, &Results);
  RemoveBadMatches(&Results);

  if (Results.NumMatches != 1) {
    if (LearningDebugLevel >= 1) {
      cprintf ("Rejecting punc = %s (Alternatives = ",
               unicharset.id_to_unichar(ClassId));

      for (i = 0; i < Results.NumMatches; i++)
        cprintf ("%s", unicharset.id_to_unichar(Results.Classes[i]));
      cprintf (")\n");
    }
    return;
  }

  #ifndef SECURE_NAMES
  if (LearningDebugLevel >= 1)
    cprintf ("Adapting to punc = %s, thr= %g\n",
             unicharset.id_to_unichar(ClassId), Threshold);
  #endif
  AdaptToChar(Blob, LineStats, ClassId, Threshold);

}                                /* AdaptToPunc */


/*---------------------------------------------------------------------------*/
void AddNewResult(ADAPT_RESULTS *Results,
                  CLASS_ID ClassId,
                  FLOAT32 Rating,
                  int ConfigId) {
/*
 **                         Parameters:
 **                         Results
              results to add new result to
**                          ClassId
              class of new result
**                          Rating
              rating of new result
**                          ConfigId
              config id of new result
**                          Globals:
**                          BadMatchPad
              defines limits of an acceptable match
**                          Operation: This routine adds the result of a classification into
**                          Results.  If the new rating is much worse than the current
**                          best rating, it is not entered into results because it
**                          would end up being stripped later anyway.  If the new rating
**                          is better than the old rating for the class, it replaces the
**                          old rating.  If this is the first rating for the class, the
**                          class is added to the list of matched classes in Results.
**                          If the new rating is better than the best so far, it
**                          becomes the best so far.
**                          Return: none
**                          Exceptions: none
**                          History: Tue Mar 12 18:19:29 1991, DSJ, Created.
*/
  FLOAT32 OldRating;
  INT_CLASS_STRUCT* CharClass = NULL;

  OldRating = Results->Ratings[ClassId];
  if (Rating <= Results->BestRating + BadMatchPad && Rating < OldRating) {
    Results->Ratings[ClassId] = Rating;
    if (ClassId != NO_CLASS)
      CharClass = ClassForClassId(PreTrainedTemplates, ClassId);
    if (CharClass != NULL && CharClass->NumConfigs == 32)
      Results->Configs[ClassId] = ConfigId;
    else
      Results->Configs[ClassId] = ~0;

    if (Rating < Results->BestRating) {
      Results->BestRating = Rating;
      Results->BestClass = ClassId;
      Results->BestConfig = ConfigId;
    }

    /* if this is first rating for class, add to list of classes matched */
    if (OldRating == WORST_POSSIBLE_RATING)
      Results->Classes[Results->NumMatches++] = ClassId;
  }
}                                /* AddNewResult */


/*---------------------------------------------------------------------------*/
void AmbigClassifier(TBLOB *Blob,
                     LINE_STATS *LineStats,
                     INT_TEMPLATES Templates,
                     UNICHAR_ID *Ambiguities,
                     ADAPT_RESULTS *Results) {
/*
 **                         Parameters:
 **                         Blob
              blob to be classified
**                          LineStats
              statistics for text line Blob is in
**                          Templates
              built-in templates to classify against
**                          Ambiguities
              array of class id's to match against
**                          Results
              place to put match results
**                          Globals:
**                          AllProtosOn
              mask that enables all protos
**                          AllConfigsOn
              mask that enables all configs
**                          Operation: This routine is identical to CharNormClassifier()
**                          except that it does no class pruning.  It simply matches
**                          the unknown blob against the classes listed in
**                          Ambiguities.
**                          Return: none
**                          Exceptions: none
**                          History: Tue Mar 12 19:40:36 1991, DSJ, Created.
*/
  int NumFeatures;
  INT_FEATURE_ARRAY IntFeatures;
  CLASS_NORMALIZATION_ARRAY CharNormArray;
  INT_RESULT_STRUCT IntResult;
  CLASS_ID ClassId;
  CLASS_INDEX ClassIndex;

  AmbigClassifierCalls++;

  NumFeatures = GetCharNormFeatures (Blob, LineStats,
    Templates,
    IntFeatures, CharNormArray,
    &(Results->BlobLength));
  if (NumFeatures <= 0)
    return;

  if (MatcherDebugLevel >= 2)
    cprintf ("AM Matches =  ");

  while (*Ambiguities >= 0) {
    ClassId = *Ambiguities;
    ClassIndex = Templates->IndexFor[ClassId];

    SetCharNormMatch();
    IntegerMatcher (ClassForClassId (Templates, ClassId),
      AllProtosOn, AllConfigsOn,
      Results->BlobLength, NumFeatures, IntFeatures,
      CharNormArray[ClassIndex], &IntResult, NO_DEBUG);

    if (MatcherDebugLevel >= 2)
      cprintf ("%s-%-2d %2.0f  ", unicharset.id_to_unichar(ClassId),
               IntResult.Config,
               IntResult.Rating * 100.0);

    AddNewResult (Results, ClassId, IntResult.Rating, IntResult.Config);

    Ambiguities++;

    NumAmbigClassesTried++;
  }
  if (MatcherDebugLevel >= 2)
    cprintf ("\n");

}                                /* AmbigClassifier */

/*---------------------------------------------------------------------------*/
// Factored-out calls to IntegerMatcher based on class pruner results.
// Returns integer matcher results inside CLASS_PRUNER_RESULTS structure.
void MasterMatcher(INT_TEMPLATES templates,
                   inT16 num_features,
                   INT_FEATURE_ARRAY features,
                   CLASS_NORMALIZATION_ARRAY norm_factors,
                   ADAPT_CLASS* classes,
                   int debug,
                   int num_classes,
                   CLASS_PRUNER_RESULTS results,
                   ADAPT_RESULTS* final_results) {
  for (int c = 0; c < num_classes; c++) {
    CLASS_ID class_id = results[c].Class;
    INT_RESULT_STRUCT& int_result = results[c].IMResult;
    CLASS_INDEX class_index = templates->IndexFor[class_id];
    BIT_VECTOR protos = classes != NULL ? classes[class_index]->PermProtos
                                        : AllProtosOn;
    BIT_VECTOR configs = classes != NULL ? classes[class_index]->PermConfigs
                                         : AllConfigsOn;

    IntegerMatcher(ClassForClassId(templates, class_id),
                   protos, configs, final_results->BlobLength,
                   num_features, features, norm_factors[class_index],
                   &int_result, NO_DEBUG);
    // Compute class feature corrections.
    double miss_penalty = tessedit_class_miss_scale *
                          int_result.FeatureMisses;
    if (MatcherDebugLevel >= 2 || display_ratings > 1) {
      cprintf("%s-%-2d %2.1f(CP%2.1f, IM%2.1f + MP%2.1f)  ",
              unicharset.id_to_unichar(class_id), int_result.Config,
              (int_result.Rating + miss_penalty) * 100.0,
              results[c].Rating * 100.0,
              int_result.Rating * 100.0, miss_penalty * 100.0);
      if (c % 4 == 3)
        cprintf ("\n");
    }
    int_result.Rating += miss_penalty;
    if (int_result.Rating > WORST_POSSIBLE_RATING)
      int_result.Rating = WORST_POSSIBLE_RATING;
    AddNewResult(final_results, class_id, int_result.Rating, int_result.Config);
  }
  if (MatcherDebugLevel >= 2 || display_ratings > 1)
    cprintf("\n");
}

/*---------------------------------------------------------------------------*/
UNICHAR_ID *BaselineClassifier(TBLOB *Blob,
                               LINE_STATS *LineStats,
                               ADAPT_TEMPLATES Templates,
                               ADAPT_RESULTS *Results) {
/*
 **                         Parameters:
 **                         Blob
              blob to be classified
**                          LineStats
              statistics for text line Blob is in
**                          Templates
              current set of adapted templates
**                          Results
              place to put match results
**                          Globals:
**                          BaselineCutoffs
              expected num features for each class
**                          Operation: This routine extracts baseline normalized features
**                          from the unknown character and matches them against the
**                          specified set of templates.  The classes which match
**                          are added to Results.
**                          Return: Array of possible ambiguous chars that should be checked.
**                          Exceptions: none
**                          History: Tue Mar 12 19:38:03 1991, DSJ, Created.
*/
  int NumFeatures;
  int NumClasses;
  INT_FEATURE_ARRAY IntFeatures;
  CLASS_NORMALIZATION_ARRAY CharNormArray;
  CLASS_ID ClassId;
  CLASS_INDEX ClassIndex;

  BaselineClassifierCalls++;

  NumFeatures = GetBaselineFeatures (Blob, LineStats,
    Templates->Templates,
    IntFeatures, CharNormArray,
    &(Results->BlobLength));
  if (NumFeatures <= 0)
    return NULL;

  NumClasses = ClassPruner (Templates->Templates, NumFeatures,
    IntFeatures, CharNormArray,
    BaselineCutoffs, Results->CPResults,
    MatchDebugFlags);

  NumBaselineClassesTried += NumClasses;

  if (MatcherDebugLevel >= 2 || display_ratings > 1)
    cprintf ("BL Matches =  ");

  SetBaseLineMatch();
  MasterMatcher(Templates->Templates, NumFeatures, IntFeatures, CharNormArray,
                Templates->Class, MatchDebugFlags, NumClasses,
                Results->CPResults, Results);

  ClassId = Results->BestClass;
  if (ClassId == NO_CLASS)
    return (NULL);
  /* this is a bug - maybe should return "" */

  ClassIndex = Templates->Templates->IndexFor[ClassId];
  return (Templates->Class[ClassIndex]->
    Config[Results->BestConfig].Perm);
}                                /* BaselineClassifier */


/*---------------------------------------------------------------------------*/
void CharNormClassifier(TBLOB *Blob,
                        LINE_STATS *LineStats,
                        INT_TEMPLATES Templates,
                        ADAPT_RESULTS *Results) {
/*
 **                         Parameters:
 **                         Blob
              blob to be classified
**                          LineStats
              statistics for text line Blob is in
**                          Templates
              templates to classify unknown against
**                          Results
              place to put match results
**                          Globals:
**                          CharNormCutoffs
              expected num features for each class
**                          AllProtosOn
              mask that enables all protos
**                          AllConfigsOn
              mask that enables all configs
**                          Operation: This routine extracts character normalized features
**                          from the unknown character and matches them against the
**                          specified set of templates.  The classes which match
**                          are added to Results.
**                          Return: none
**                          Exceptions: none
**                          History: Tue Mar 12 16:02:52 1991, DSJ, Created.
*/
  int NumFeatures;
  int NumClasses;
  INT_FEATURE_ARRAY IntFeatures;
  CLASS_NORMALIZATION_ARRAY CharNormArray;

  CharNormClassifierCalls++;

  NumFeatures = GetCharNormFeatures(Blob, LineStats,
    Templates,
    IntFeatures, CharNormArray,
    &(Results->BlobLength));
  if (NumFeatures <= 0)
    return;

  NumClasses = ClassPruner(Templates, NumFeatures,
                           IntFeatures, CharNormArray,
                           CharNormCutoffs, Results->CPResults,
                           MatchDebugFlags);

  if (tessedit_single_match && NumClasses > 1)
    NumClasses = 1;
  NumCharNormClassesTried += NumClasses;

  if (MatcherDebugLevel >= 2 || display_ratings > 1)
    cprintf("CN Matches =  ");

  SetCharNormMatch();
  MasterMatcher(Templates, NumFeatures, IntFeatures, CharNormArray,
                NULL, MatchDebugFlags, NumClasses,
                Results->CPResults, Results);
}                                /* CharNormClassifier */


/*---------------------------------------------------------------------------*/
void ClassifyAsNoise(TBLOB *Blob,
                     LINE_STATS *LineStats,
                     ADAPT_RESULTS *Results) {
/*
 **                         Parameters:
 **                         Blob
              blob to be classified
**                          LineStats
              statistics for text line Blob is in
**                          Results
              results to add noise classification to
**                          Globals:
**                          NoiseBlobLength
              avg. length of a noise blob
**                          Operation: This routine computes a rating which reflects the
**                          likelihood that the blob being classified is a noise
**                          blob.  NOTE: assumes that the blob length has already been
**                          computed and placed into Results.
**                          Return: none
**                          Exceptions: none
**                          History: Tue Mar 12 18:36:52 1991, DSJ, Created.
*/
  register FLOAT32 Rating;

  Rating = Results->BlobLength / NoiseBlobLength;
  Rating *= Rating;
  Rating /= 1.0 + Rating;

  AddNewResult (Results, NO_CLASS, Rating, 0);
}                                /* ClassifyAsNoise */


/*---------------------------------------------------------------------------*/
int CompareCurrentRatings(                     //CLASS_ID              *Class1,
                          const void *arg1,
                          const void *arg2) {  //CLASS_ID              *Class2)
/*
 **                         Parameters:
 **                         Class1, Class2
              classes whose ratings are to be compared
**                          Globals:
**                          CurrentRatings
              contains actual ratings for each class
**                          Operation: This routine gets the ratings for the 2 specified classes
**                          from a global variable (CurrentRatings) and returns:
**          -1 if Rating1 < Rating2
**                          0 if Rating1 = Rating2
**                          1 if Rating1 > Rating2
**                          Return: Order of classes based on their ratings (see above).
**                          Exceptions: none
**                          History: Tue Mar 12 14:18:31 1991, DSJ, Created.
*/
  FLOAT32 Rating1, Rating2;
  CLASS_ID *Class1 = (CLASS_ID *) arg1;
  CLASS_ID *Class2 = (CLASS_ID *) arg2;

  Rating1 = CurrentRatings[*Class1];
  Rating2 = CurrentRatings[*Class2];

  if (Rating1 < Rating2)
    return (-1);
  else if (Rating1 > Rating2)
    return (1);
  else
    return (0);

}                                /* CompareCurrentRatings */


/*---------------------------------------------------------------------------*/
LIST ConvertMatchesToChoices(ADAPT_RESULTS *Results) {
/*
 **                         Parameters:
 **                         Results
              adaptive matcher results to convert to choices
**                          Globals: none
**                          Operation: This routine creates a choice for each matching class
**                          in Results (up to MAX_MATCHES) and returns a list of
**                          these choices.  The match
**                          ratings are converted to be the ratings and certainties
**                          as used by the context checkers.
**                          Return: List of choices.
**                          Exceptions: none
**                          History: Tue Mar 12 08:55:37 1991, DSJ, Created.
*/
  int i;
  LIST Choices;
  CLASS_ID NextMatch;
  FLOAT32 Rating;
  FLOAT32 Certainty;
  const char *NextMatch_unichar;
  char choice_lengths[2] = {0, 0};

  if (Results->NumMatches > MAX_MATCHES)
    Results->NumMatches = MAX_MATCHES;

  for (Choices = NIL, i = 0; i < Results->NumMatches; i++) {
    NextMatch = Results->Classes[i];
    Rating = Certainty = Results->Ratings[NextMatch];
    Rating *= RatingScale * Results->BlobLength;
    Certainty *= -CertaintyScale;
    if (NextMatch != NO_CLASS)
      NextMatch_unichar = unicharset.id_to_unichar(NextMatch);
    else
      NextMatch_unichar = "";
    choice_lengths[0] = strlen(NextMatch_unichar);
    Choices = append_choice (Choices,
                             NextMatch_unichar,
                             choice_lengths,
                             Rating, Certainty,
                             Results->Configs[NextMatch],
                             unicharset.get_script(NextMatch));
  }
  return (Choices);

}                                /* ConvertMatchesToChoices */


/*---------------------------------------------------------------------------*/
#ifndef GRAPHICS_DISABLED
void DebugAdaptiveClassifier(TBLOB *Blob,
                             LINE_STATS *LineStats,
                             ADAPT_RESULTS *Results) {
/*
 **                         Parameters:
 **                         Blob
              blob whose classification is being debugged
**                          LineStats
              statistics for text line blob is in
**                          Results
              results of match being debugged
**                          Globals: none
**                          Operation:
**                          Return: none
**                          Exceptions: none
**                          History: Wed Mar 13 16:44:41 1991, DSJ, Created.
*/
  const char *Prompt =
    "Left-click in IntegerMatch Window to continue or right click to debug...";
  const char *DebugMode = "All Templates";
  CLASS_ID LastClass = Results->BestClass;
  CLASS_ID ClassId;
  BOOL8 AdaptiveOn = TRUE;
  BOOL8 PreTrainedOn = TRUE;

  ShowMatchDisplay();
  cprintf ("\nDebugging class = %s  (%s) ...\n",
           unicharset.id_to_unichar(LastClass), DebugMode);
  ShowBestMatchFor(Blob, LineStats, LastClass, AdaptiveOn, PreTrainedOn);
  UpdateMatchDisplay();

  while ((ClassId = GetClassToDebug (Prompt)) != 0) {
#if 0
    switch (ClassId) {
      case 'b':
        AdaptiveOn = TRUE;
        PreTrainedOn = FALSE;
        DebugMode = "Adaptive Templates Only";
        break;

      case 'c':
        AdaptiveOn = FALSE;
        PreTrainedOn = TRUE;
        DebugMode = "PreTrained Templates Only";
        break;

      case 'a':
        AdaptiveOn = TRUE;
        PreTrainedOn = TRUE;
        DebugMode = "All Templates";
        break;

      default:
        LastClass = ClassId;
        break;
    }
#endif
    LastClass = ClassId;

    ShowMatchDisplay();
    cprintf ("\nDebugging class = %d = %s  (%s) ...\n",
             LastClass, unicharset.id_to_unichar(LastClass), DebugMode);
    ShowBestMatchFor(Blob, LineStats, LastClass, AdaptiveOn, PreTrainedOn);
    UpdateMatchDisplay();
  }
}                                /* DebugAdaptiveClassifier */
#endif

/*---------------------------------------------------------------------------*/
void DoAdaptiveMatch(TBLOB *Blob,
                     LINE_STATS *LineStats,
                     ADAPT_RESULTS *Results) {
/*
 **                         Parameters:
 **                         Blob
              blob to be classified
**                          LineStats
              statistics for text line Blob is in
**                          Results
              place to put match results
**                          Globals:
**                          PreTrainedTemplates
              built-in training templates
**                          AdaptedTemplates
              templates adapted for this page
**                          GreatAdaptiveMatch
              rating limit for a great match
**                          Operation: This routine performs an adaptive classification.
**                          If we have not yet adapted to enough classes, a simple
**                          classification to the pre-trained templates is performed.
**                          Otherwise, we match the blob against the adapted templates.
**                          If the adapted templates do not match well, we try a
**                          match against the pre-trained templates.  If an adapted
**                          template match is found, we do a match to any pre-trained
**                          templates which could be ambiguous.  The results from all
**                          of these classifications are merged together into Results.
**                          Return: none
**                          Exceptions: none
**                          History: Tue Mar 12 08:50:11 1991, DSJ, Created.
*/
  UNICHAR_ID *Ambiguities;

  AdaptiveMatcherCalls++;
  InitIntFX();

  if (AdaptedTemplates->NumPermClasses < MinNumPermClasses
  || tess_cn_matching) {
    CharNormClassifier(Blob, LineStats, PreTrainedTemplates, Results);
  }
  else {
    Ambiguities = BaselineClassifier (Blob, LineStats,
      AdaptedTemplates, Results);

    if ((Results->NumMatches > 0 && MarginalMatch (Results->BestRating)
    && !tess_bn_matching) || Results->NumMatches == 0) {
      CharNormClassifier(Blob, LineStats, PreTrainedTemplates, Results);
    }
    else if (Ambiguities && *Ambiguities >= 0) {
      AmbigClassifier(Blob,
                      LineStats,
                      PreTrainedTemplates,
                      Ambiguities,
                      Results);
    }
  }

  if (Results->NumMatches == 0)
    ClassifyAsNoise(Blob, LineStats, Results);
  /**/}   /* DoAdaptiveMatch */

  /*---------------------------------------------------------------------------*/
  void
  GetAdaptThresholds (TWERD * Word,
  LINE_STATS * LineStats,
  const WERD_CHOICE& BestChoice,
  const WERD_CHOICE& BestRawChoice, FLOAT32 Thresholds[]) {
  /*
   **                           Parameters:
   **                           Word
                current word
  **                            LineStats
                line stats for row word is in
  **                            BestChoice
                best choice for current word with context
  **                            BestRawChoice
                best choice for current word without context
  **                            Thresholds
                array of thresholds to be filled in
  **                            Globals:
  **                            EnableNewAdaptRules
  **                            GoodAdaptiveMatch
  **                            PerfectRating
  **                            RatingMargin
  **                            Operation: This routine tries to estimate how tight the adaptation
  **                            threshold should be set for each character in the current
  **                            word.  In general, the routine tries to set tighter
  **                            thresholds for a character when the current set of templates
  **                            would have made an error on that character.  It tries
  **                            to set a threshold tight enough to eliminate the error.
  **                            Two different sets of rules can be used to determine the
  **                            desired thresholds.
  **                            Return: none (results are returned in Thresholds)
  **                            Exceptions: none
  **                            History: Fri May 31 09:22:08 1991, DSJ, Created.
  */
    TBLOB *Blob;
    const char* BestChoice_string = BestChoice.string().string();
    const char* BestChoice_lengths = BestChoice.lengths().string();
    const char* BestRawChoice_string = BestRawChoice.string().string();
    const char* BestRawChoice_lengths = BestRawChoice.lengths().string();

    if (EnableNewAdaptRules &&   /* new rules */
        CurrentBestChoiceIs (BestChoice_string, BestChoice_lengths)) {
      FindClassifierErrors(PerfectRating,
                           GoodAdaptiveMatch,
                           RatingMargin,
                           Thresholds);
    }
    else {                       /* old rules */
      for (Blob = Word->blobs;
        Blob != NULL;
        Blob = Blob->next, BestChoice_string += *(BestChoice_lengths++),
               BestRawChoice_string += *(BestRawChoice_lengths++), Thresholds++)
        if (*(BestChoice_lengths) == *(BestRawChoice_lengths) &&
            strncmp(BestChoice_string, BestRawChoice_string,
                    *(BestChoice_lengths)) == 0)
        *Thresholds = GoodAdaptiveMatch;
      else {
        /* the blob was incorrectly classified - find the rating threshold
           needed to create a template which will correct the error with
           some margin.  However, don't waste time trying to make
           templates which are too tight. */
        *Thresholds = GetBestRatingFor (Blob, LineStats,
                                        unicharset.unichar_to_id(
                                            BestChoice_string,
                                            *BestChoice_lengths));
        *Thresholds *= (1.0 - RatingMargin);
        if (*Thresholds > GoodAdaptiveMatch)
          *Thresholds = GoodAdaptiveMatch;
        if (*Thresholds < PerfectRating)
          *Thresholds = PerfectRating;
      }
    }
  }                              /* GetAdaptThresholds */

  /*---------------------------------------------------------------------------*/
  UNICHAR_ID *GetAmbiguities(TBLOB *Blob,
                             LINE_STATS *LineStats,
                             CLASS_ID CorrectClass) {
  /*
   **                           Parameters:
   **                           Blob
                blob to get classification ambiguities for
  **                            LineStats
                statistics for text line blob is in
  **                            CorrectClass
                correct class for Blob
  **                            Globals:
  **                            CurrentRatings
                used by qsort compare routine
  **                            PreTrainedTemplates
                built-in templates
  **                            Operation: This routine matches blob to the built-in templates
  **                            to find out if there are any classes other than the correct
  **                            class which are potential ambiguities.
  **                            Return: String containing all possible ambiguous classes.
  **                            Exceptions: none
  **                            History: Fri Mar 15 08:08:22 1991, DSJ, Created.
  */
    ADAPT_RESULTS Results;
    UNICHAR_ID *Ambiguities;
    int i;

    EnterClassifyMode;

    Results.NumMatches = 0;
    Results.BestRating = WORST_POSSIBLE_RATING;
    Results.BestClass = NO_CLASS;
    Results.BestConfig = 0;
    InitMatcherRatings (Results.Ratings);

    CharNormClassifier(Blob, LineStats, PreTrainedTemplates, &Results);
    RemoveBadMatches(&Results);

    /* save ratings in a global so that CompareCurrentRatings() can see them */
    CurrentRatings = Results.Ratings;
    qsort ((void *) (Results.Classes), Results.NumMatches,
      sizeof (CLASS_ID), CompareCurrentRatings);

    /* copy the class id's into an string of ambiguities - don't copy if
       the correct class is the only class id matched */
    Ambiguities = (UNICHAR_ID *) Emalloc (sizeof (UNICHAR_ID) *
                                          (Results.NumMatches + 1));
    if (Results.NumMatches > 1 ||
    (Results.NumMatches == 1 && Results.Classes[0] != CorrectClass)) {
      for (i = 0; i < Results.NumMatches; i++)
        Ambiguities[i] = Results.Classes[i];
      Ambiguities[i] = -1;
    }
    else
      Ambiguities[0] = -1;

    return (Ambiguities);

  }                              /* GetAmbiguities */

  /*---------------------------------------------------------------------------*/
  int GetBaselineFeatures(TBLOB *Blob,
                          LINE_STATS *LineStats,
                          INT_TEMPLATES Templates,
                          INT_FEATURE_ARRAY IntFeatures,
                          CLASS_NORMALIZATION_ARRAY CharNormArray,
                          inT32 *BlobLength) {
  /*
   **                           Parameters:
   **                           Blob
                blob to extract features from
  **                            LineStats
                statistics about text row blob is in
  **                            Templates
                used to compute char norm adjustments
  **                            IntFeatures
                array to fill with integer features
  **                            CharNormArray
                array to fill with dummy char norm adjustments
  **                            BlobLength
                length of blob in baseline-normalized units
  **                            Globals: none
  **                            Operation: This routine sets up the feature extractor to extract
  **                            baseline normalized pico-features.
  **                            The extracted pico-features are converted
  **                            to integer form and placed in IntFeatures.  CharNormArray
  **                            is filled with 0's to indicate to the matcher that no
  **                            character normalization adjustment needs to be done.
  **                            The total length of all blob outlines
  **                            in baseline normalized units is also returned.
  **                            Return: Number of pico-features returned (0 if an error occurred)
  **                            Exceptions: none
  **                            History: Tue Mar 12 17:55:18 1991, DSJ, Created.
  */
    FEATURE_SET Features;
    int NumFeatures;

    if (EnableIntFX)
      return (GetIntBaselineFeatures (Blob, LineStats, Templates,
        IntFeatures, CharNormArray, BlobLength));

    NormMethod = baseline;
    Features = ExtractPicoFeatures (Blob, LineStats);

    NumFeatures = Features->NumFeatures;
    *BlobLength = NumFeatures;
    if (NumFeatures > UNLIKELY_NUM_FEAT) {
      FreeFeatureSet(Features);
      return (0);
    }

    ComputeIntFeatures(Features, IntFeatures);
    ClearCharNormArray(Templates, CharNormArray);

    FreeFeatureSet(Features);
    return (NumFeatures);

  }                              /* GetBaselineFeatures */

  /*---------------------------------------------------------------------------*/
  FLOAT32 GetBestRatingFor(TBLOB *Blob,
                           LINE_STATS *LineStats,
                           CLASS_ID ClassId) {
  /*
   **                           Parameters:
   **                           Blob
                blob to get best rating for
  **                            LineStats
                statistics about text line blob is in
  **                            ClassId
                class blob is to be compared to
  **                            Globals:
  **                            PreTrainedTemplates
                built-in templates
  **                            AdaptedTemplates
                current set of adapted templates
  **                            AllProtosOn
                dummy mask to enable all protos
  **                            AllConfigsOn
                dummy mask to enable all configs
  **                            Operation: This routine classifies Blob against both sets of
  **                            templates for the specified class and returns the best
  **                            rating found.
  **                            Return: Best rating for match of Blob to ClassId.
  **                            Exceptions: none
  **                            History: Tue Apr  9 09:01:24 1991, DSJ, Created.
  */
    int NumCNFeatures, NumBLFeatures;
    INT_FEATURE_ARRAY CNFeatures, BLFeatures;
    INT_RESULT_STRUCT CNResult, BLResult;
    CLASS_NORMALIZATION_ARRAY CNAdjust, BLAdjust;
    CLASS_INDEX ClassIndex;
    inT32 BlobLength;

    CNResult.Rating = BLResult.Rating = 1.0;

    if (!LegalClassId (ClassId))
      return (1.0);

    if (!UnusedClassIdIn (PreTrainedTemplates, ClassId)) {
      NumCNFeatures = GetCharNormFeatures (Blob, LineStats,
        PreTrainedTemplates,
        CNFeatures, CNAdjust, &BlobLength);
      if (NumCNFeatures > 0) {
        ClassIndex = PreTrainedTemplates->IndexFor[ClassId];

        SetCharNormMatch();
        IntegerMatcher (ClassForClassId (PreTrainedTemplates, ClassId),
          AllProtosOn, AllConfigsOn,
          BlobLength, NumCNFeatures, CNFeatures,
          CNAdjust[ClassIndex], &CNResult, NO_DEBUG);
      }
    }

    if (!UnusedClassIdIn (AdaptedTemplates->Templates, ClassId)) {
      NumBLFeatures = GetBaselineFeatures (Blob, LineStats,
        AdaptedTemplates->Templates,
        BLFeatures, BLAdjust, &BlobLength);
      if (NumBLFeatures > 0) {
        ClassIndex = AdaptedTemplates->Templates->IndexFor[ClassId];

        SetBaseLineMatch();
        IntegerMatcher (ClassForClassId
          (AdaptedTemplates->Templates, ClassId),
          AdaptedTemplates->Class[ClassIndex]->PermProtos,
          AdaptedTemplates->Class[ClassIndex]->PermConfigs,
          BlobLength, NumBLFeatures, BLFeatures,
          BLAdjust[ClassIndex], &BLResult, NO_DEBUG);
      }
    }

    return (MIN (BLResult.Rating, CNResult.Rating));

  }                              /* GetBestRatingFor */

  /*---------------------------------------------------------------------------*/
  int GetCharNormFeatures(TBLOB *Blob,
                          LINE_STATS *LineStats,
                          INT_TEMPLATES Templates,
                          INT_FEATURE_ARRAY IntFeatures,
                          CLASS_NORMALIZATION_ARRAY CharNormArray,
                          inT32 *BlobLength) {
  /*
   **                           Parameters:
   **                           Blob
                blob to extract features from
  **                            LineStats
                statistics about text row blob is in
  **                            Templates
                used to compute char norm adjustments
  **                            IntFeatures
                array to fill with integer features
  **                            CharNormArray
                array to fill with char norm adjustments
  **                            BlobLength
                length of blob in baseline-normalized units
  **                            Globals: none
  **                            Operation: This routine sets up the feature extractor to extract
  **                            character normalization features and character normalized
  **                            pico-features.  The extracted pico-features are converted
  **                            to integer form and placed in IntFeatures.  The character
  **                            normalization features are matched to each class in
  **                            templates and the resulting adjustment factors are returned
  **                            in CharNormArray.  The total length of all blob outlines
  **                            in baseline normalized units is also returned.
  **                            Return: Number of pico-features returned (0 if an error occurred)
  **                            Exceptions: none
  **                            History: Tue Mar 12 17:55:18 1991, DSJ, Created.
  */
    return (GetIntCharNormFeatures (Blob, LineStats, Templates,
      IntFeatures, CharNormArray, BlobLength));
  }                              /* GetCharNormFeatures */

  /*---------------------------------------------------------------------------*/
  int GetIntBaselineFeatures(TBLOB *Blob,
                             LINE_STATS *LineStats,
                             INT_TEMPLATES Templates,
                             INT_FEATURE_ARRAY IntFeatures,
                             CLASS_NORMALIZATION_ARRAY CharNormArray,
                             inT32 *BlobLength) {
  /*
   **                           Parameters:
   **                           Blob
                blob to extract features from
  **                            LineStats
                statistics about text row blob is in
  **                            Templates
                used to compute char norm adjustments
  **                            IntFeatures
                array to fill with integer features
  **                            CharNormArray
                array to fill with dummy char norm adjustments
  **                            BlobLength
                length of blob in baseline-normalized units
  **                            Globals:
  **                            FeaturesHaveBeenExtracted
                TRUE if fx has been done
  **                            BaselineFeatures
                holds extracted baseline feat
  **                            CharNormFeatures
                holds extracted char norm feat
  **                            FXInfo
                holds misc. FX info
  **                            Operation: This routine calls the integer (Hardware) feature
  **                            extractor if it has not been called before for this blob.
  **                            The results from the feature extractor are placed into
  **                            globals so that they can be used in other routines without
  **                            re-extracting the features.
  **                            It then copies the baseline features into the IntFeatures
  **                            array provided by the caller.
  **                            Return: Number of features extracted or 0 if an error occured.
  **                            Exceptions: none
  **                            History: Tue May 28 10:40:52 1991, DSJ, Created.
  */
    register INT_FEATURE Src, Dest, End;

    if (!FeaturesHaveBeenExtracted) {
      FeaturesOK = ExtractIntFeat (Blob, BaselineFeatures,
        CharNormFeatures, &FXInfo);
      FeaturesHaveBeenExtracted = TRUE;
    }

    if (!FeaturesOK) {
      *BlobLength = FXInfo.NumBL;
      return (0);
    }

    for (Src = BaselineFeatures, End = Src + FXInfo.NumBL, Dest = IntFeatures;
      Src < End; *Dest++ = *Src++);

    ClearCharNormArray(Templates, CharNormArray);
    *BlobLength = FXInfo.NumBL;
    return (FXInfo.NumBL);

  }                              /* GetIntBaselineFeatures */

  /*---------------------------------------------------------------------------*/
  int GetIntCharNormFeatures(TBLOB *Blob,
                             LINE_STATS *LineStats,
                             INT_TEMPLATES Templates,
                             INT_FEATURE_ARRAY IntFeatures,
                             CLASS_NORMALIZATION_ARRAY CharNormArray,
                             inT32 *BlobLength) {
  /*
   **                           Parameters:
   **                           Blob
                blob to extract features from
  **                            LineStats
                statistics about text row blob is in
  **                            Templates
                used to compute char norm adjustments
  **                            IntFeatures
                array to fill with integer features
  **                            CharNormArray
                array to fill with dummy char norm adjustments
  **                            BlobLength
                length of blob in baseline-normalized units
  **                            Globals:
  **                            FeaturesHaveBeenExtracted
                TRUE if fx has been done
  **                            BaselineFeatures
                holds extracted baseline feat
  **                            CharNormFeatures
                holds extracted char norm feat
  **                            FXInfo
                holds misc. FX info
  **                            Operation: This routine calls the integer (Hardware) feature
  **                            extractor if it has not been called before for this blob.
  **                            The results from the feature extractor are placed into
  **                            globals so that they can be used in other routines without
  **                            re-extracting the features.
  **                            It then copies the char norm features into the IntFeatures
  **                            array provided by the caller.
  **                            Return: Number of features extracted or 0 if an error occured.
  **                            Exceptions: none
  **                            History: Tue May 28 10:40:52 1991, DSJ, Created.
  */
    register INT_FEATURE Src, Dest, End;
    FEATURE NormFeature;
    FLOAT32 Baseline, Scale;

    if (!FeaturesHaveBeenExtracted) {
      FeaturesOK = ExtractIntFeat (Blob, BaselineFeatures,
        CharNormFeatures, &FXInfo);
      FeaturesHaveBeenExtracted = TRUE;
    }

    if (!FeaturesOK) {
      *BlobLength = FXInfo.NumBL;
      return (0);
    }

    for (Src = CharNormFeatures, End = Src + FXInfo.NumCN, Dest = IntFeatures;
      Src < End; *Dest++ = *Src++);

    NormFeature = NewFeature (&CharNormDesc);
    Baseline = BaselineAt (LineStats, FXInfo.Xmean);
    Scale = ComputeScaleFactor (LineStats);
    NormFeature->Params[CharNormY] = (FXInfo.Ymean - Baseline) * Scale;
    NormFeature->Params[CharNormLength] =
      FXInfo.Length * Scale / LENGTH_COMPRESSION;
    NormFeature->Params[CharNormRx] = FXInfo.Rx * Scale;
    NormFeature->Params[CharNormRy] = FXInfo.Ry * Scale;
    ComputeIntCharNormArray(NormFeature, Templates, CharNormArray);
    FreeFeature(NormFeature);

    *BlobLength = FXInfo.NumBL;
    return (FXInfo.NumCN);

  }                              /* GetIntCharNormFeatures */

  /*---------------------------------------------------------------------------*/
  void InitMatcherRatings(register FLOAT32 *Rating) {
  /*
   **                           Parameters:
   **                           Rating
                ptr to array of ratings to be initialized
  **                            Globals: none
  **                            Operation: This routine initializes the best rating for each class
  **                            to be the worst possible rating (1.0).
  **                            Return: none
  **                            Exceptions: none
  **                            History: Tue Mar 12 13:43:28 1991, DSJ, Created.
  */
    register FLOAT32 *LastRating;
    register FLOAT32 WorstRating = WORST_POSSIBLE_RATING;

    for (LastRating = Rating + MAX_CLASS_ID;
      Rating <= LastRating; *Rating++ = WorstRating);

  }                              /* InitMatcherRatings */

  /*---------------------------------------------------------------------------*/
  int MakeNewTemporaryConfig(ADAPT_TEMPLATES Templates,
                              CLASS_ID ClassId,
                              int NumFeatures,
                              INT_FEATURE_ARRAY Features,
                              FEATURE_SET FloatFeatures) {
  /*
   **                           Parameters:
   **                           Templates
                adapted templates to add new config to
  **                            ClassId
                class id to associate with new config
  **                            NumFeatures
                number of features in IntFeatures
  **                            Features
                features describing model for new config
  **                            FloatFeatures
                floating-pt representation of features
  **                            Globals:
  **                            AllProtosOn
                mask to enable all protos
  **                            AllConfigsOff
                mask to disable all configs
  **                            TempProtoMask
                defines old protos matched in new config
  **                            Operation:
  **                            Return: The id of the new config created, a negative integer in
  **                                                    case of error.
  **                            Exceptions: none
  **                            History: Fri Mar 15 08:49:46 1991, DSJ, Created.
  */
    CLASS_INDEX ClassIndex;
    INT_CLASS IClass;
    ADAPT_CLASS Class;
    PROTO_ID OldProtos[MAX_NUM_PROTOS];
    FEATURE_ID BadFeatures[MAX_NUM_INT_FEATURES];
    int NumOldProtos;
    int NumBadFeatures;
    int MaxProtoId, OldMaxProtoId;
    int BlobLength = 0;
    int MaskSize;
    int ConfigId;
    TEMP_CONFIG Config;
    int i;
    int debug_level = NO_DEBUG;

    if (LearningDebugLevel >= 3)
      debug_level =
        PRINT_MATCH_SUMMARY | PRINT_FEATURE_MATCHES | PRINT_PROTO_MATCHES;

    ClassIndex = Templates->Templates->IndexFor[ClassId];
    IClass = ClassForClassId (Templates->Templates, ClassId);
    Class = Templates->Class[ClassIndex];

    if (IClass->NumConfigs >= MAX_NUM_CONFIGS)
    {
      ++NumAdaptationsFailed;
      if (LearningDebugLevel >= 1)
        cprintf ("Cannot make new temporary config: maximum number exceeded.\n");
      return -1;
    }

    OldMaxProtoId = IClass->NumProtos - 1;

    NumOldProtos = FindGoodProtos (IClass, AllProtosOn, AllConfigsOff,
      BlobLength, NumFeatures, Features,
      OldProtos, debug_level);

    MaskSize = WordsInVectorOfSize (MAX_NUM_PROTOS);
    zero_all_bits(TempProtoMask, MaskSize);
    for (i = 0; i < NumOldProtos; i++)
      SET_BIT (TempProtoMask, OldProtos[i]);

    NumBadFeatures = FindBadFeatures (IClass, TempProtoMask, AllConfigsOn,
      BlobLength, NumFeatures, Features,
      BadFeatures, debug_level);

    MaxProtoId = MakeNewTempProtos (FloatFeatures, NumBadFeatures, BadFeatures,
      IClass, Class, TempProtoMask);
    if (MaxProtoId == NO_PROTO)
    {
      ++NumAdaptationsFailed;
      if (LearningDebugLevel >= 1)
        cprintf ("Cannot make new temp protos: maximum number exceeded.\n");
      return -1;
    }

    ConfigId = AddIntConfig (IClass);
    ConvertConfig(TempProtoMask, ConfigId, IClass);
    Config = NewTempConfig (MaxProtoId);
    TempConfigFor (Class, ConfigId) = Config;
    copy_all_bits (TempProtoMask, Config->Protos, Config->ProtoVectorSize);

    if (LearningDebugLevel >= 1)
      cprintf ("Making new temp config %d using %d old and %d new protos.\n",
        ConfigId, NumOldProtos, MaxProtoId - OldMaxProtoId);

    return ConfigId;
  }                              /* MakeNewTemporaryConfig */

  /*---------------------------------------------------------------------------*/
  PROTO_ID
  MakeNewTempProtos (FEATURE_SET Features,
  int NumBadFeat,
  FEATURE_ID BadFeat[],
  INT_CLASS IClass,
  ADAPT_CLASS Class, BIT_VECTOR TempProtoMask) {
  /*
   **                           Parameters:
   **                           Features
                floating-pt features describing new character
  **                            NumBadFeat
                number of bad features to turn into protos
  **                            BadFeat
                feature id's of bad features
  **                            IClass
                integer class templates to add new protos to
  **                            Class
                adapted class templates to add new protos to
  **                            TempProtoMask
                proto mask to add new protos to
  **                            Globals: none
  **                            Operation: This routine finds sets of sequential bad features
  **                            that all have the same angle and converts each set into
  **                            a new temporary proto.  The temp proto is added to the
  **                            proto pruner for IClass, pushed onto the list of temp
  **                            protos in Class, and added to TempProtoMask.
  **                            Return: Max proto id in class after all protos have been added.
  **                            Exceptions: none
  **                            History: Fri Mar 15 11:39:38 1991, DSJ, Created.
  */
    FEATURE_ID *ProtoStart;
    FEATURE_ID *ProtoEnd;
    FEATURE_ID *LastBad;
    TEMP_PROTO TempProto;
    PROTO Proto;
    FEATURE F1, F2;
    FLOAT32 X1, X2, Y1, Y2;
    FLOAT32 A1, A2, AngleDelta;
    FLOAT32 SegmentLength;
    PROTO_ID Pid;

    for (ProtoStart = BadFeat, LastBad = ProtoStart + NumBadFeat;
    ProtoStart < LastBad; ProtoStart = ProtoEnd) {
      F1 = Features->Features[*ProtoStart];
      X1 = F1->Params[PicoFeatX];
      Y1 = F1->Params[PicoFeatY];
      A1 = F1->Params[PicoFeatDir];

      for (ProtoEnd = ProtoStart + 1,
        SegmentLength = GetPicoFeatureLength ();
        ProtoEnd < LastBad;
      ProtoEnd++, SegmentLength += GetPicoFeatureLength ()) {
        F2 = Features->Features[*ProtoEnd];
        X2 = F2->Params[PicoFeatX];
        Y2 = F2->Params[PicoFeatY];
        A2 = F2->Params[PicoFeatDir];

        AngleDelta = fabs (A1 - A2);
        if (AngleDelta > 0.5)
          AngleDelta = 1.0 - AngleDelta;

        if (AngleDelta > MaxAngleDelta ||
          fabs (X1 - X2) > SegmentLength ||
          fabs (Y1 - Y2) > SegmentLength)
          break;
      }

      F2 = Features->Features[*(ProtoEnd - 1)];
      X2 = F2->Params[PicoFeatX];
      Y2 = F2->Params[PicoFeatY];
      A2 = F2->Params[PicoFeatDir];

      Pid = AddIntProto (IClass);
      if (Pid == NO_PROTO)
        return (NO_PROTO);

      TempProto = NewTempProto ();
      Proto = &(TempProto->Proto);

      /* compute proto params - NOTE that Y_DIM_OFFSET must be used because
         ConvertProto assumes that the Y dimension varies from -0.5 to 0.5
         instead of the -0.25 to 0.75 used in baseline normalization */
      Proto->Length = SegmentLength;
      Proto->Angle = A1;
      Proto->X = (X1 + X2) / 2.0;
      Proto->Y = (Y1 + Y2) / 2.0 - Y_DIM_OFFSET;
      FillABC(Proto);

      TempProto->ProtoId = Pid;
      SET_BIT(TempProtoMask, Pid);

      ConvertProto(Proto, Pid, IClass);
      AddProtoToProtoPruner(Proto, Pid, IClass);

      Class->TempProtos = push (Class->TempProtos, TempProto);
    }
    return (IClass->NumProtos - 1);
  }                              /* MakeNewTempProtos */

  /*---------------------------------------------------------------------------*/
  void MakePermanent(ADAPT_TEMPLATES Templates,
                     CLASS_ID ClassId,
                     int ConfigId,
                     TBLOB *Blob,
                     LINE_STATS *LineStats) {
  /*
   **                           Parameters:
   **                           Templates
                current set of adaptive templates
  **                            ClassId
                class containing config to be made permanent
  **                            ConfigId
                config to be made permanent
  **                            Blob
                current blob being adapted to
  **                            LineStats
                statistics about text line Blob is in
  **                            Globals: none
  **                            Operation:
  **                            Return: none
  **                            Exceptions: none
  **                            History: Thu Mar 14 15:54:08 1991, DSJ, Created.
  */
    UNICHAR_ID *Ambigs;
    TEMP_CONFIG Config;
    CLASS_INDEX ClassIndex;
    ADAPT_CLASS Class;
    PROTO_KEY ProtoKey;

    ClassIndex = Templates->Templates->IndexFor[ClassId];
    Class = Templates->Class[ClassIndex];
    Config = TempConfigFor (Class, ConfigId);

    MakeConfigPermanent(Class, ConfigId);
    if (Class->NumPermConfigs == 0)
      Templates->NumPermClasses++;
    Class->NumPermConfigs++;

    ProtoKey.Templates = Templates;
    ProtoKey.ClassId = ClassId;
    ProtoKey.ConfigId = ConfigId;
    Class->TempProtos = delete_d (Class->TempProtos, &ProtoKey,
      MakeTempProtoPerm);
    FreeTempConfig(Config);

    Ambigs = GetAmbiguities (Blob, LineStats, ClassId);
    PermConfigFor (Class, ConfigId) = Ambigs;

    if (LearningDebugLevel >= 1) {
      cprintf ("Making config %d permanent with ambiguities '",
               ConfigId, Ambigs);
      for (UNICHAR_ID *AmbigsPointer = Ambigs;
           *AmbigsPointer >= 0; ++AmbigsPointer)
        cprintf("%s", unicharset.id_to_unichar(*AmbigsPointer));
      cprintf("'.\n");
    }

  }                              /* MakePermanent */

  /*---------------------------------------------------------------------------*/
  int MakeTempProtoPerm(void *item1,    //TEMP_PROTO    TempProto,
                        void *item2) {  //PROTO_KEY             *ProtoKey)
  /*
   **                           Parameters:
   **                           TempProto
                temporary proto to compare to key
  **                            ProtoKey
                defines which protos to make permanent
  **                            Globals: none
  **                            Operation: This routine converts TempProto to be permanent if
  **                            its proto id is used by the configuration specified in
  **                            ProtoKey.
  **                            Return: TRUE if TempProto is converted, FALSE otherwise
  **                            Exceptions: none
  **                            History: Thu Mar 14 18:49:54 1991, DSJ, Created.
  */
    CLASS_INDEX ClassIndex;
    ADAPT_CLASS Class;
    TEMP_CONFIG Config;
    TEMP_PROTO TempProto;
    PROTO_KEY *ProtoKey;

    TempProto = (TEMP_PROTO) item1;
    ProtoKey = (PROTO_KEY *) item2;

    ClassIndex = ProtoKey->Templates->Templates->IndexFor[ProtoKey->ClassId];
    Class = ProtoKey->Templates->Class[ClassIndex];
    Config = TempConfigFor (Class, ProtoKey->ConfigId);

    if (TempProto->ProtoId > Config->MaxProtoId ||
      !test_bit (Config->Protos, TempProto->ProtoId))
      return (FALSE);

    MakeProtoPermanent (Class, TempProto->ProtoId);
    AddProtoToClassPruner (&(TempProto->Proto), ProtoKey->ClassId,
      ProtoKey->Templates->Templates);
    FreeTempProto(TempProto);

    return (TRUE);

  }                              /* MakeTempProtoPerm */

  /*---------------------------------------------------------------------------*/
  int NumBlobsIn(TWERD *Word) {
  /*
   **                           Parameters:
   **                           Word
                word to count blobs in
  **                            Globals: none
  **                            Operation: This routine returns the number of blobs in Word.
  **                            Return: Number of blobs in Word.
  **                            Exceptions: none
  **                            History: Thu Mar 14 08:30:27 1991, DSJ, Created.
  */
    register TBLOB *Blob;
    register int NumBlobs;

    if (Word == NULL)
      return (0);

    for (Blob = Word->blobs, NumBlobs = 0;
      Blob != NULL; Blob = Blob->next, NumBlobs++);

    return (NumBlobs);

  }                              /* NumBlobsIn */

  /*---------------------------------------------------------------------------*/
  int NumOutlinesInBlob(TBLOB *Blob) {
  /*
   **                           Parameters:
   **                           Blob
                blob to count outlines in
  **                            Globals: none
  **                            Operation: This routine returns the number of OUTER outlines
  **                            in Blob.
  **                            Return: Number of outer outlines in Blob.
  **                            Exceptions: none
  **                            History: Mon Jun 10 15:46:20 1991, DSJ, Created.
  */
    register TESSLINE *Outline;
    register int NumOutlines;

    if (Blob == NULL)
      return (0);

    for (Outline = Blob->outlines, NumOutlines = 0;
      Outline != NULL; Outline = Outline->next, NumOutlines++);

    return (NumOutlines);

  }                              /* NumOutlinesInBlob */

  /*---------------------------------------------------------------------------*/
  void PrintAdaptiveMatchResults(FILE *File, ADAPT_RESULTS *Results) {
  /*
   **                           Parameters:
   **                           File
                open text file to write Results to
  **                            Results
                match results to write to File
  **                            Globals: none
  **                            Operation: This routine writes the matches in Results to File.
  **                            Return: none
  **                            Exceptions: none
  **                            History: Mon Mar 18 09:24:53 1991, DSJ, Created.
  */
    for (int i = 0; i < Results->NumMatches; ++i) {
      cprintf("%s(%d) %.2f  ",
               unicharset.debug_str(Results->Classes[i]).string(),
               Results->Classes[i],
               Results->Ratings[Results->Classes[i]] * 100.0);
    }
  }                              /* PrintAdaptiveMatchResults */

  /*---------------------------------------------------------------------------*/
  void RemoveBadMatches(ADAPT_RESULTS *Results) {
  /*
   **                           Parameters:
   **                           Results
                contains matches to be filtered
  **                            Globals:
  **                            BadMatchPad
                defines a "bad match"
  **                            Operation: This routine steps thru each matching class in Results
  **                            and removes it from the match list if its rating
  **                            is worse than the BestRating plus a pad.  In other words,
  **                            all good matches get moved to the front of the classes
  **                            array.
  **                            Return: none
  **                            Exceptions: none
  **                            History: Tue Mar 12 13:51:03 1991, DSJ, Created.
  */
    int Next, NextGood;
    FLOAT32 *Rating = Results->Ratings;
    CLASS_ID *Match = Results->Classes;
    FLOAT32 BadMatchThreshold;
    static const char* romans = "i v x I V X";
    BadMatchThreshold = Results->BestRating + BadMatchPad;

    if (bln_numericmode) {
      UNICHAR_ID unichar_id_one = unicharset.contains_unichar("1") ?
          unicharset.unichar_to_id("1") : -1;
      UNICHAR_ID unichar_id_zero = unicharset.contains_unichar("0") ?
          unicharset.unichar_to_id("0") : -1;
      for (Next = NextGood = 0; Next < Results->NumMatches; Next++) {
        if (Rating[Match[Next]] <= BadMatchThreshold) {
          if (!unicharset.get_isalpha(Match[Next]) ||
              strstr(romans, unicharset.id_to_unichar(Match[Next])) != NULL) {
            Match[NextGood++] = Match[Next];
          } else if (unichar_id_one >= 0 && unicharset.eq(Match[Next], "l") &&
                     Rating[unichar_id_one] >= BadMatchThreshold) {
            Match[NextGood++] = unichar_id_one;
            Rating[unichar_id_one] = Rating[unicharset.unichar_to_id("l")];
          } else if (unichar_id_zero >= 0 && unicharset.eq(Match[Next], "O") &&
                     Rating[unichar_id_zero] >= BadMatchThreshold) {
              Match[NextGood++] = unichar_id_zero;
              Rating[unichar_id_zero] = Rating[unicharset.unichar_to_id("O")];
          }
        }
      }
    }
    else {
      for (Next = NextGood = 0; Next < Results->NumMatches; Next++) {
        if (Rating[Match[Next]] <= BadMatchThreshold)
          Match[NextGood++] = Match[Next];
      }
    }

    Results->NumMatches = NextGood;

  }                              /* RemoveBadMatches */

  /*----------------------------------------------------------------------------------*/
  void RemoveExtraPuncs(ADAPT_RESULTS *Results) {
  /*
   **                           Parameters:
   **                           Results
                contains matches to be filtered
  **                            Globals:
  **                            BadMatchPad
                defines a "bad match"
  **                            Operation: This routine steps thru each matching class in Results
  **                            and removes it from the match list if its rating
  **                            is worse than the BestRating plus a pad.  In other words,
  **                            all good matches get moved to the front of the classes
  **                            array.
  **                            Return: none
  **                            Exceptions: none
  **                            History: Tue Mar 12 13:51:03 1991, DSJ, Created.
  */
    int Next, NextGood;
    int punc_count;              /*no of garbage characters */
    int digit_count;
    CLASS_ID *Match = Results->Classes;
                                 /*garbage characters */
    static char punc_chars[] = ". , ; : / ` ~ ' - = \\ | \" ! _ ^";
    static char digit_chars[] = "0 1 2 3 4 5 6 7 8 9";

    punc_count = 0;
    digit_count = 0;
    for (Next = NextGood = 0; Next < Results->NumMatches; Next++) {
      if (strstr (punc_chars,
                  unicharset.id_to_unichar(Match[Next])) == NULL) {
        if (strstr (digit_chars,
                    unicharset.id_to_unichar(Match[Next])) == NULL) {
          Match[NextGood++] = Match[Next];
        }
        else {
          if (digit_count < 1)
            Match[NextGood++] = Match[Next];
          digit_count++;
        }
      }
      else {
        if (punc_count < 2)
          Match[NextGood++] = Match[Next];
        punc_count++;            /*count them */
      }
    }
    Results->NumMatches = NextGood;
  }                              /* RemoveExtraPuncs */

  /*---------------------------------------------------------------------------*/
  void SetAdaptiveThreshold(FLOAT32 Threshold) {
  /*
   **                           Parameters:
   **                           Threshold
                threshold for creating new templates
  **                            Globals:
  **                            GoodAdaptiveMatch
                default good match rating
  **                            Operation: This routine resets the internal thresholds inside
  **                            the integer matcher to correspond to the specified
  **                            threshold.
  **                            Return: none
  **                            Exceptions: none
  **                            History: Tue Apr  9 08:33:13 1991, DSJ, Created.
  */
    if (Threshold == GoodAdaptiveMatch) {
      /* the blob was probably classified correctly - use the default rating
         threshold */
      SetProtoThresh (0.9);
      SetFeatureThresh (0.9);
    }
    else {
      /* the blob was probably incorrectly classified */
      SetProtoThresh (1.0 - Threshold);
      SetFeatureThresh (1.0 - Threshold);
    }
  }                              /* SetAdaptiveThreshold */

  /*---------------------------------------------------------------------------*/
  void ShowBestMatchFor(TBLOB *Blob,
                        LINE_STATS *LineStats,
                        CLASS_ID ClassId,
                        BOOL8 AdaptiveOn,
                        BOOL8 PreTrainedOn) {
  /*
   **                           Parameters:
   **                           Blob
                blob to show best matching config for
  **                            LineStats
                statistics for text line Blob is in
  **                            ClassId
                class whose configs are to be searched
  **                            AdaptiveOn
                TRUE if adaptive configs are enabled
  **                            PreTrainedOn
                TRUE if pretrained configs are enabled
  **                            Globals:
  **                            PreTrainedTemplates
                built-in training
  **                            AdaptedTemplates
                adaptive templates
  **                            AllProtosOn
                dummy proto mask
  **                            AllConfigsOn
                dummy config mask
  **                            Operation: This routine compares Blob to both sets of templates
  **        (adaptive and pre-trained) and then displays debug
  **                            information for the config which matched best.
  **                            Return: none
  **                            Exceptions: none
  **                            History: Fri Mar 22 08:43:52 1991, DSJ, Created.
  */
    int NumCNFeatures = 0, NumBLFeatures = 0;
    INT_FEATURE_ARRAY CNFeatures, BLFeatures;
    INT_RESULT_STRUCT CNResult, BLResult;
    CLASS_NORMALIZATION_ARRAY CNAdjust, BLAdjust;
    CLASS_INDEX ClassIndex;
    inT32 BlobLength;
    uinT32 ConfigMask;
    static int next_config = -1;

    if (PreTrainedOn) next_config = -1;

    CNResult.Rating = BLResult.Rating = 2.0;

    if (!LegalClassId (ClassId)) {
      cprintf ("%d is not a legal class id!!\n", ClassId);
      return;
    }

    if (PreTrainedOn) {
      if (UnusedClassIdIn (PreTrainedTemplates, ClassId))
        cprintf ("No built-in templates for class %d = %s\n",
                 ClassId, unicharset.id_to_unichar(ClassId));
      else {
        NumCNFeatures = GetCharNormFeatures (Blob, LineStats,
          PreTrainedTemplates,
          CNFeatures, CNAdjust,
          &BlobLength);
        if (NumCNFeatures <= 0)
          cprintf ("Illegal blob (char norm features)!\n");
        else {
          ClassIndex = PreTrainedTemplates->IndexFor[ClassId];

          SetCharNormMatch();
          IntegerMatcher (ClassForClassId (PreTrainedTemplates, ClassId),
            AllProtosOn, AllConfigsOn,
            BlobLength, NumCNFeatures, CNFeatures,
            CNAdjust[ClassIndex], &CNResult, NO_DEBUG);

          cprintf ("Best built-in template match is config %2d (%4.1f) (cn=%d)\n",
            CNResult.Config, CNResult.Rating * 100.0, CNAdjust[ClassIndex]);
        }
      }
    }

    if (AdaptiveOn) {
      if (UnusedClassIdIn (AdaptedTemplates->Templates, ClassId))
        cprintf ("No AD templates for class %d = %s\n",
                 ClassId, unicharset.id_to_unichar(ClassId));
      else {
        NumBLFeatures = GetBaselineFeatures (Blob, LineStats,
          AdaptedTemplates->Templates,
          BLFeatures, BLAdjust,
          &BlobLength);
        if (NumBLFeatures <= 0)
          cprintf ("Illegal blob (baseline features)!\n");
        else {
          ClassIndex =AdaptedTemplates->Templates->IndexFor[ClassId];

          SetBaseLineMatch();
          IntegerMatcher (ClassForClassId
            (AdaptedTemplates->Templates, ClassId),
                          AllProtosOn, AllConfigsOn,
  //          AdaptedTemplates->Class[ClassIndex]->PermProtos,
  //          AdaptedTemplates->Class[ClassIndex]->PermConfigs,
            BlobLength, NumBLFeatures, BLFeatures,
            BLAdjust[ClassIndex], &BLResult, NO_DEBUG);

          #ifndef SECURE_NAMES
          int ClassIndex = AdaptedTemplates->Templates->IndexFor[ClassId];
          ADAPT_CLASS Class = AdaptedTemplates->Class[ClassIndex];
          cprintf ("Best adaptive template match is config %2d (%4.1f) %s\n",
                   BLResult.Config, BLResult.Rating * 100.0,
                   ConfigIsPermanent(Class, BLResult.Config) ? "Perm" : "Temp");
          #endif
        }
      }
    }

    cprintf ("\n");
    if (BLResult.Rating < CNResult.Rating) {
      ClassIndex = AdaptedTemplates->Templates->IndexFor[ClassId];
      if (next_config < 0) {
        ConfigMask = 1 << BLResult.Config;
        next_config = 0;
      } else {
        ConfigMask = 1 << next_config;
        ++next_config;
      }
      NormMethod = baseline;

      SetBaseLineMatch();
      IntegerMatcher (ClassForClassId (AdaptedTemplates->Templates, ClassId),
                      AllProtosOn,
//        AdaptedTemplates->Class[ClassIndex]->PermProtos,
        (BIT_VECTOR) & ConfigMask,
        BlobLength, NumBLFeatures, BLFeatures,
        BLAdjust[ClassIndex], &BLResult, MatchDebugFlags);
      cprintf ("Adaptive template match for config %2d is %4.1f\n",
        BLResult.Config, BLResult.Rating * 100.0);
    }
    else {
      ClassIndex = PreTrainedTemplates->IndexFor[ClassId];
      ConfigMask = 1 << CNResult.Config;
      NormMethod = character;

      SetCharNormMatch();
                                 //xiaofan
      IntegerMatcher (ClassForClassId (PreTrainedTemplates, ClassId), AllProtosOn, (BIT_VECTOR) & ConfigMask,
        BlobLength, NumCNFeatures, CNFeatures,
        CNAdjust[ClassIndex], &CNResult, MatchDebugFlags);
    }
  }                              /* ShowBestMatchFor */