summaryrefslogtreecommitdiff
path: root/src/spell.c
blob: e3a97fc83342d980187b8f991b5d382684839684 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
/* vi:set ts=8 sts=4 sw=4:
 *
 * VIM - Vi IMproved	by Bram Moolenaar
 *
 * Do ":help uganda"  in Vim to read copying and usage conditions.
 * Do ":help credits" in Vim to see a list of people who contributed.
 * See README.txt for an overview of the Vim source code.
 */

/*
 * spell.c: code for spell checking
 *
 * Terminology:
 * "dword" is a dictionary word, made out of letters and digits.
 * "nword" is a word with a character that's not a letter or digit.
 * "word"  is either a "dword" or an "nword".
 */

/*
 * Why doesn't Vim use aspell/ispell/myspell/etc.?
 * See ":help develop-spell".
 */

#if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
# include <io.h>	/* for lseek(), must be before vim.h */
#endif

#include "vim.h"

#if defined(FEAT_SYN_HL) || defined(PROTO)

#ifdef HAVE_FCNTL_H
# include <fcntl.h>
#endif

#define MAXWLEN 100		/* assume max. word len is this many bytes */

/*
 * Structure that is used to store the text from the language file.  This
 * avoids the need to allocate space for each individual word.  It's allocated
 * in big chunks for speed.
 */
#define  SBLOCKSIZE 4096	/* default size of sb_data */
typedef struct sblock_S sblock_T;
struct sblock_S
{
    sblock_T	*sb_next;	/* next block in list */
    char_u	sb_data[1];	/* data, actually longer */
};

/* Info from "REP" entries in ".aff" file used in af_rep. */
typedef struct repentry_S
{
    char_u	*re_from;
    char_u	*re_to;
} repentry_T;

/*
 * Structure to store affix info.
 */
typedef struct affitem_S affitem_T;
struct affitem_S
{
    affitem_T	*ai_next;	/* next affix with same ai_add[] or NULL */
    short_u	ai_nr;		/* affix number */
    char_u	ai_combine;	/* prefix combines with suffix */
    char_u	ai_choplen;	/* length of ai_chop in bytes */
    char_u	ai_addlen;	/* length of ai_add in bytes */
    char_u	*ai_chop;	/* text chopped off basic word (can be NULL) */
    char_u	ai_add[1];	/* text added to basic word (actually longer) */
};

/* Get affitem_T pointer from hashitem that uses ai_add */
static affitem_T dumai;
#define HI2AI(hi)	((affitem_T *)((hi)->hi_key - (dumai.ai_add - (char_u *)&dumai)))

/*
 * Structure used to store words and other info for one language.
 */
typedef struct slang_S slang_T;
struct slang_S
{
    slang_T	*sl_next;	/* next language */
    char_u	*sl_name;	/* language name "en", "en.rare", "nl", etc. */
    hashtab_T	sl_words;	/* main word table, fword_T */
    int		sl_prefcnt;	/* number of prefix NRs */
    garray_T	sl_preftab;	/* list of hashtables to lookup prefixes */
    affitem_T	*sl_prefzero;	/* list of prefixes with zero add length */
    int		sl_suffcnt;	/* number of suffix NRs */
    garray_T	sl_sufftab;	/* list of hashtables to lookup suffixes */
    affitem_T	*sl_suffzero;	/* list of suffixes with zero add length */
    char_u	*sl_try;	/* "TRY" from .aff file */
    garray_T	sl_rep;		/* list of repentry_T entries from REP lines */
    char_u	sl_regions[17];	/* table with up to 8 region names plus NUL */
    sblock_T	*sl_block;	/* list with allocated memory blocks */
    int		sl_error;	/* error while loading */
};

static slang_T *first_lang = NULL;

/*
 * Structure to store an addition to a basic word.
 */
typedef struct addword_S addword_T;
struct addword_S
{
    addword_T	*aw_next;	/* next addition */
    char_u	aw_flags;	/* ADD_ flags */
    char_u	aw_leadlen;	/* length of lead in bytes */
    char_u	aw_wordlen;	/* length of aw_word in bytes */
    char_u	aw_region;	/* region for word with this addition */
    char_u	aw_word[1];	/* text, actually longer: case-folded addition
				   plus, with ADD_KEEPCAP: keep-case addition */
};

/*
 * Structure to store a basic word.
 */
typedef struct fword_S fword_T;
struct fword_S
{
    fword_T	*fw_next;	/* same basic word with different caps */
    char_u	fw_region;	/* region bits */
    char_u	fw_prefixcnt;	/* number of prefix numbers */
    char_u	fw_suffixcnt;	/* number of suffix numbers */
    short_u	fw_flags;	/* BWF_ flags */
    void	*fw_prefix;	/* table with prefix numbers */
    void	*fw_suffix;	/* table with suffix numbers */
    addword_T	*fw_adds;	/* first addword_T entry */
    char_u	fw_word[1];	/* actually longer: case folded word, or
				   keep-case word when (flags & BWF_KEEPCAP) */
};

/* Get fword_T pointer from hashitem that uses fw_word */
static fword_T dumfw;
#define HI2FWORD(hi)	((fword_T *)((hi)->hi_key - (dumfw.fw_word - (char_u *)&dumfw)))

#define REGION_ALL 0xff


/*
 * Structure used in "b_langp", filled from 'spelllang'.
 */
typedef struct langp_S
{
    slang_T	*lp_slang;	/* info for this language (NULL for last one) */
    int		lp_region;	/* bitmask for region or REGION_ALL */
} langp_T;

#define LANGP_ENTRY(ga, i)	(((langp_T *)(ga).ga_data) + (i))

#define SP_OK		0
#define SP_BAD		1
#define SP_RARE		2
#define SP_LOCAL	3

/* flags used for basic words in the spell file */
#define BWF_VALID	0x01	    /* word is valid without additions */
#define BWF_REGION	0x02	    /* region byte follows */
#define BWF_ONECAP	0x04	    /* first letter must be capital */
#define BWF_SUFFIX	0x08	    /* has suffix NR list */
#define BWF_SECOND	0x10	    /* second flags byte follows */

#define BWF_ADDS	0x0100	    /* there are additions */
#define BWF_PREFIX	0x0200	    /* has prefix NR list */
#define BWF_ALLCAP	0x0400	    /* all letters must be capital (not used
				       for single-letter words) */
#define BWF_KEEPCAP	0x0800	    /* Keep case as-is */

/* flags used for addition in the spell file */
#define ADD_REGION	0x02	    /* region byte follows */
#define ADD_ONECAP	0x04	    /* first letter must be capital */
#define ADD_ALLCAP	0x40	    /* all letters must be capital (not used
				       for single-letter words) */
#define ADD_KEEPCAP	0x80	    /* fixed case */

/* Translate ADD_ flags to BWF_ flags.
 * (Needed to keep ADD_ flags in one byte.) */
#define ADD2BWF(x)	(((x) & 0x0f) | (((x) & 0xf0) << 4))

#define VIMSPELLMAGIC "VIMspell01"  /* string at start of Vim spell file */
#define VIMSPELLMAGICL 10

/*
 * Structure to store info for word matching.
 */
typedef struct matchinf_S
{
    langp_T	*mi_lp;			/* info for language and region */
    slang_T	*mi_slang;		/* info for the language */
    char_u	*mi_line;		/* start of line containing word */
    char_u	*mi_word;		/* start of word being checked */
    char_u	*mi_end;		/* first non-word char after mi_word */
    char_u	*mi_wend;		/* end of matching word (is "mi_end"
					 * or further) */
    char_u	*mi_cword;		/* word to check, can be "mi_fword" */
    char_u	mi_fword[MAXWLEN + 1];	/* "mi_word" to "mi_end" case-folded */
    int		mi_faddlen;		/* length of valid bytes in "mi_fadd" */
    char_u	*mi_faddp;		/* next char to be added to "mi_fadd" */
    char_u	mi_fadd[MAXWLEN + 1];	/* "mi_end" and further case-folded */
    int		mi_result;		/* result so far: SP_BAD, SP_OK, etc. */
    int		mi_capflags;		/* BWF_ONECAP BWF_ALLCAP BWF_KEEPCAP */
} matchinf_T;

static int word_match __ARGS((matchinf_T *mip));
static int check_adds __ARGS((matchinf_T *mip, fword_T *fw, int req_pref, int req_suf));
static int supports_afffix __ARGS((int cnt, void *afffix, int afffixcnt, int nr));
static int prefix_match __ARGS((matchinf_T *mip));
static int suffix_match __ARGS((matchinf_T *mip));
static int match_caps __ARGS((int flags, char_u *caseword, matchinf_T *mip, char_u *cword, char_u *end));
static slang_T *slang_alloc __ARGS((char_u *lang));
static void slang_free __ARGS((slang_T *lp));
static slang_T *spell_load_lang __ARGS((char_u *lang));
static void spell_load_file __ARGS((char_u *fname, void *cookie));
static int spell_load_affixes __ARGS((FILE *fd, slang_T *lp, int *bl_usedp, int affm, void **affp));
static void *getroom __ARGS((slang_T *lp, int *bl_used, int len));
static int find_region __ARGS((char_u *rp, char_u *region));
static int captype __ARGS((char_u *word, char_u *end));

/*
 * Main spell-checking function.
 * "ptr" points to the start of a word.
 * "*attrp" is set to the attributes for a badly spelled word.  For a non-word
 * or when it's OK it remains unchanged.
 * This must only be called when 'spelllang' is not empty.
 * Returns the length of the word in bytes, also when it's OK, so that the
 * caller can skip over the word.
 */
    int
spell_check(wp, line, ptr, attrp)
    win_T	*wp;		/* current window */
    char_u	*line;		/* start of line where "ptr" points into */
    char_u	*ptr;
    int		*attrp;
{
    matchinf_T	mi;		/* Most things are put in "mi" so that it can
				   be passed to functions quickly. */

    /* Find the end of the word.  We already know that *ptr is a word char. */
    mi.mi_word = ptr;
    mi.mi_end = ptr;
    do
    {
	mb_ptr_adv(mi.mi_end);
    } while (*mi.mi_end != NUL && spell_iswordc(mi.mi_end));

    /* A word starting with a number is always OK. */
    if (*ptr >= '0' && *ptr <= '9')
	return (int)(mi.mi_end - ptr);

    /* Make case-folded copy of the Word.  Compute its hash value. */
    (void)str_foldcase(ptr, mi.mi_end - ptr, mi.mi_fword, MAXWLEN + 1);
    mi.mi_cword = mi.mi_fword;

    /* The word is bad unless we find it in the dictionary. */
    mi.mi_result = SP_BAD;
    mi.mi_wend = mi.mi_end;
    mi.mi_faddp = mi.mi_end;
    mi.mi_faddlen = 0;
    mi.mi_capflags = captype(ptr, mi.mi_end);
    mi.mi_line = line;

    /*
     * Loop over the languages specified in 'spelllang'.
     * We check them all, because a matching word may have additions that are
     * longer than an already found matching word.
     */
    for (mi.mi_lp = LANGP_ENTRY(wp->w_buffer->b_langp, 0);
				       mi.mi_lp->lp_slang != NULL; ++mi.mi_lp)
    {
	/*
	 * Check for a matching word.
	 * If not found or wrong region try removing prefixes (and then
	 * suffixes).
	 * If still not found or wrong region try removing suffixes.
	 */
	mi.mi_slang = mi.mi_lp->lp_slang;
	if (!word_match(&mi) || mi.mi_result != SP_OK)
	    if (!prefix_match(&mi) || mi.mi_result != SP_OK)
		suffix_match(&mi);
    }

    if (mi.mi_result != SP_OK)
    {
	if (mi.mi_result == SP_BAD)
	    *attrp = highlight_attr[HLF_SPB];
	else if (mi.mi_result == SP_RARE)
	    *attrp = highlight_attr[HLF_SPR];
	else
	    *attrp = highlight_attr[HLF_SPL];
    }

    return (int)(mi.mi_wend - ptr);
}

/*
 * Check if the word "mip->mi_cword" matches.
 */
    static int
word_match(mip)
    matchinf_T *mip;
{
    hash_T	fhash = hash_hash(mip->mi_cword);
    hashitem_T	*hi;
    fword_T	*fw;
    int		valid = FALSE;

    hi = hash_lookup(&mip->mi_slang->sl_words, mip->mi_cword, fhash);
    if (HASHITEM_EMPTY(hi))
	return FALSE;

    /*
     * Find a basic word for which the case of word "cword" is correct.
     * If it is, check additions and use the longest one.
     */
    for (fw = HI2FWORD(hi); fw != NULL; fw = fw->fw_next)
	if (match_caps(fw->fw_flags, fw->fw_word, mip,
						   mip->mi_word, mip->mi_end))
	    valid |= check_adds(mip, fw, -1, -1);

    return valid;
}

/*
 * Check a matching basic word for additions.
 * Return TRUE if we have a valid match.
 */
    static int
check_adds(mip, fw, req_pref, req_suf)
    matchinf_T	*mip;
    fword_T	*fw;
    int		req_pref;	/* required prefix nr, -1 if none */
    int		req_suf;	/* required suffix nr, -1 if none */
{
    int		valid = FALSE;
    addword_T	*aw;
    char_u	*p;
    int		addlen;
    int		fl;

    /* A word may be valid without additions. */
    if ((fw->fw_flags & BWF_VALID)
	    && (req_pref < 0 || supports_afffix(mip->mi_slang->sl_prefcnt,
				   fw->fw_prefix, fw->fw_prefixcnt, req_pref))
	    && (req_suf < 0 || supports_afffix(mip->mi_slang->sl_suffcnt,
				   fw->fw_suffix, fw->fw_suffixcnt, req_suf)))
    {
	valid = TRUE;
	if (mip->mi_result != SP_OK)
	{
	    if ((fw->fw_region & mip->mi_lp->lp_region) == 0)
		mip->mi_result = SP_LOCAL;
	    else
		mip->mi_result = SP_OK;
	}
    }

    /*
     * Check additions, both before and after the word.
     * This may make the word longer, thus we also need to check
     * when we already found a matching word.
     */
    for (aw = fw->fw_adds; aw != NULL; aw = aw->aw_next)
    {
	if (aw->aw_leadlen > 0)
	{
	    /* There is a leader, verify that it matches. */
	    if (aw->aw_leadlen > mip->mi_word - mip->mi_line
		    || STRNCMP(mip->mi_word - aw->aw_leadlen,
					    aw->aw_word, aw->aw_leadlen) != 0)
		continue;
	    if (mip->mi_word - aw->aw_leadlen > mip->mi_line)
	    {
		/* There must not be a word character just before the
		 * leader. */
		p = mip->mi_word - aw->aw_leadlen;
		mb_ptr_back(mip->mi_line, p);
		if (spell_iswordc(p))
		    continue;
	    }
	    /* Leader matches.  Addition is rest of "aw_word". */
	    p = aw->aw_word + aw->aw_leadlen;
	}
	else
	    /* No leader, use whole of "aw_word" for addition. */
	    p = aw->aw_word;

	addlen = aw->aw_wordlen - aw->aw_leadlen;
	if (addlen > 0)
	{
	    /* Check for matching addition and no word character after it.
	     * First make sure we have enough case-folded chars to compare
	     * with. */
	    while (mip->mi_faddlen <= addlen)
	    {
		if (*mip->mi_faddp == NUL)
		{
		    mip->mi_fadd[mip->mi_faddlen] = NUL;
		    break;
		}
#ifdef FEAT_MBYTE
		fl = (*mb_ptr2len_check)(mip->mi_faddp);
#else
		fl = 1;
#endif
		(void)str_foldcase(mip->mi_faddp, fl,
				   mip->mi_fadd + mip->mi_faddlen,
						   MAXWLEN - mip->mi_faddlen);
		mip->mi_faddp += fl;
		mip->mi_faddlen += STRLEN(mip->mi_fadd + mip->mi_faddlen);
	    }

	    if (STRNCMP(mip->mi_fadd, p, addlen) != 0
		    || (mip->mi_fadd[addlen] != NUL
				     && spell_iswordc(mip->mi_fadd + addlen)))
		continue;

	    /* Compute the length in the original word, before case folding. */
#ifdef FEAT_MBYTE
	    if (has_mbyte)
	    {
		int	l;

		p = mip->mi_end;
		for (l = 0; l < addlen;
				   l += (*mb_ptr2len_check)(mip->mi_fadd + l))
		    mb_ptr_adv(p);
		addlen = p - mip->mi_end;
	    }
#endif

	    /* Check case of the addition. */
	    if (!match_caps(ADD2BWF(aw->aw_flags),
			  aw->aw_word + aw->aw_wordlen + 1, mip,
					   mip->mi_end, mip->mi_end + addlen))
		continue;
	}

	/* Match!  Use the new length if it's longer. */
	if (mip->mi_wend < mip->mi_end + addlen)
	    mip->mi_wend = mip->mi_end + addlen;

	valid = TRUE;
	if (mip->mi_result != SP_OK)
	{
	    if ((aw->aw_region & mip->mi_lp->lp_region) == 0)
		mip->mi_result = SP_LOCAL;
	    else
		mip->mi_result = SP_OK;
	}
    }

    return valid;
}

/*
 * Return TRUE if word "fw" supports afffix "nr".
 */
    static int
supports_afffix(cnt, afffix, afffixcnt, nr)
    int		cnt;
    void	*afffix;
    int		afffixcnt;
    int		nr;
{
    char_u	*pc;
    short_u	*ps;
    int		i;

    if (cnt <= 256)
    {
	/* char_u affix numbers */
	pc = afffix;
	for (i = afffixcnt; --i >= 0; )
	    if (*pc++ == nr)
		return TRUE;
    }
    else
    {
	/* short_u affix numbers */
	ps = afffix;
	for (i = afffixcnt; --i >= 0; )
	    if (*ps++ == nr)
		return TRUE;
    }
    return FALSE;
}

/*
 * Try finding a match for "mip->mi_cword" by removing prefixes.
 */
    static int
prefix_match(mip)
    matchinf_T	*mip;
{
    int		len = 0;
    int		charlen = 0;
    int		cc;
    affitem_T	*ai;
    char_u	pword[MAXWLEN + 1];
    fword_T	*fw;
    hashtab_T	*ht;
    hashitem_T	*hi;
    int		i;
    int		found_valid = FALSE;
    int		cstart_charlen = 0;
    char_u	*cstart = mip->mi_word;
    int		capflags_save = mip->mi_capflags;
    char_u	*p;

    /*
     * Check for prefixes with different character lengths.
     * Start with zero length (only chop off).
     */
    for (charlen = 0; charlen <= mip->mi_slang->sl_preftab.ga_len; ++charlen)
    {
	if (charlen > 0)
	{
#ifdef FEAT_MBYTE
	    if (has_mbyte)
		len += mb_ptr2len_check(mip->mi_cword + len);
	    else
#endif
		len += 1;
	}
	if (mip->mi_cword[len] == NUL)	/* end of word, no prefix possible */
	    break;

	if (charlen == 0)
	    ai = mip->mi_slang->sl_prefzero;
	else
	{
	    /* Get pointer to hashtab for prefix of this many chars. */
	    ht = ((hashtab_T *)mip->mi_slang->sl_preftab.ga_data) + charlen - 1;
	    if (ht->ht_used == 0)
		continue;

	    cc = mip->mi_cword[len];
	    mip->mi_cword[len] = NUL;
	    hi = hash_find(ht, mip->mi_cword);
	    mip->mi_cword[len] = cc;

	    if (HASHITEM_EMPTY(hi))
		ai = NULL;
	    else
		ai = HI2AI(hi);
	}

	/* Loop over all matching prefixes. */
	for ( ; ai != NULL; ai = ai->ai_next)
	{
	    /* Create the basic word by removing the prefix and adding the
	     * chop string. */
	    mch_memmove(pword, ai->ai_chop, ai->ai_choplen);
	    STRCPY(pword + ai->ai_choplen, mip->mi_cword + ai->ai_addlen);

	    /* Adjust the word start for case checks, we only check the
	     * part after the prefix. */
	    while (cstart_charlen < charlen)
	    {
		mb_ptr_adv(cstart);
		++cstart_charlen;
	    }

	    /* Removing the prefix may change the caps, e.g. for
	     * "deAlf" removing "de" makes it ONECAP. */
	    mip->mi_capflags = captype(cstart, mip->mi_end);

	    /* Find the basic word. */
	    hi = hash_find(&mip->mi_slang->sl_words, pword);
	    if (!HASHITEM_EMPTY(hi))
	    {
		/* Check if the word supports this prefix. */
		for (fw = HI2FWORD(hi); fw != NULL; fw = fw->fw_next)
		    if (match_caps(fw->fw_flags, fw->fw_word, mip,
							 cstart, mip->mi_end))
			found_valid |= check_adds(mip, fw, ai->ai_nr, -1);

		if (found_valid && mip->mi_result == SP_OK)
		{
		    /* Found a valid word, no need to try other suffixes. */
		    mip->mi_capflags = capflags_save;
		    return TRUE;
		}
	    }

	    /* No matching basic word without prefix.  When combining is
	     * allowed try with suffixes. */
	    if (ai->ai_combine)
	    {
		/* Pass the word with prefix removed to suffix_match(). */
		mip->mi_cword = pword;
		p = mip->mi_word;
		mip->mi_word = cstart;
		i = suffix_match(mip);
		mip->mi_cword = mip->mi_fword;
		mip->mi_word = p;
		if (i)
		{
		    mip->mi_capflags = capflags_save;
		    return TRUE;
		}
	    }
	}
    }

    mip->mi_capflags = capflags_save;
    return FALSE;
}

/*
 * Try finding a match for "mip->mi_cword" by removing suffixes.
 */
    static int
suffix_match(mip)
    matchinf_T	*mip;
{
    char_u	*sufp;
    int		charlen;
    affitem_T	*ai;
    char_u	pword[MAXWLEN + 1];
    fword_T	*fw;
    hashtab_T	*ht;
    hashitem_T	*hi;
    int		tlen;
    int		cend_charlen = 0;
    char_u	*cend = mip->mi_end;
    int		found_valid = FALSE;
    int		capflags_save = mip->mi_capflags;

    /*
     * Try suffixes of different length, starting with an empty suffix (chop
     * only, thus adds something).
     * Stop checking if there are no suffixes with so many characters.
     */
    sufp = mip->mi_cword + STRLEN(mip->mi_cword);
    for (charlen = 0; charlen <= mip->mi_slang->sl_sufftab.ga_len; ++charlen)
    {
	/* Move the pointer to the possible suffix back one character, unless
	 * doing the first round (empty suffix). */
	if (charlen > 0)
	{
	    mb_ptr_back(mip->mi_cword, sufp);
	    if (sufp <= mip->mi_cword)	/* start of word, no suffix possible */
		break;
	}

	if (charlen == 0)
	    ai = mip->mi_slang->sl_suffzero;
	else
	{
	    /* Get pointer to hashtab for suffix of this many chars. */
	    ht = ((hashtab_T *)mip->mi_slang->sl_sufftab.ga_data) + charlen - 1;
	    if (ht->ht_used == 0)
		continue;

	    hi = hash_find(ht, sufp);
	    if (HASHITEM_EMPTY(hi))
		ai = NULL;
	    else
		ai = HI2AI(hi);
	}

	if (ai != NULL)
	{
	    /* Found a list of matching suffixes.  Now check that there is one
	     * we can use. */
	    tlen = sufp - mip->mi_cword;    /* length of word without suffix */
	    mch_memmove(pword, mip->mi_cword, tlen);

	    for ( ; ai != NULL; ai = ai->ai_next)
	    {
		/* Found a matching suffix.  Create the basic word by removing
		 * the suffix and adding the chop string. */
		if (ai->ai_choplen == 0)
		    pword[tlen] = NUL;
		else
		    mch_memmove(pword + tlen, ai->ai_chop, ai->ai_choplen + 1);

		/* Find the basic word. */
		hi = hash_find(&mip->mi_slang->sl_words, pword);
		if (!HASHITEM_EMPTY(hi))
		{
		    /* Adjust the end for case checks, we only check the part
		     * before the suffix. */
		    while (cend_charlen < charlen)
		    {
			mb_ptr_back(mip->mi_word, cend);
			++cend_charlen;
		    }

		    /* Removing the suffix may change the caps, e.g. for
		     * "UFOs" removing 's' makes it ALLCAP. */
		    mip->mi_capflags = captype(mip->mi_word, cend);

		    /* Check if the word supports this suffix. */
		    for (fw = HI2FWORD(hi); fw != NULL; fw = fw->fw_next)
			if (match_caps(fw->fw_flags, fw->fw_word, mip,
							  mip->mi_word, cend))
			    found_valid |= check_adds(mip, fw, -1, ai->ai_nr);

		    if (found_valid && mip->mi_result == SP_OK)
		    {
			/* Found a valid word, no need to try other suffixes. */
			mip->mi_capflags = capflags_save;
			return TRUE;
		    }
		}
	    }
	}
    }

    mip->mi_capflags = capflags_save;
    return FALSE;
}

/*
 * Return TRUE if case of "cword" meets the requirements of case flags
 * "flags".
 */
    static int
match_caps(flags, caseword, mip, cword, end)
    int		flags;	    /* flags required by basic word or addition */
    char_u	*caseword;  /* word with case as required */
    matchinf_T	*mip;
    char_u	*cword;	    /* word to compare against "caseword" */
    char_u	*end;	    /* end of "cword" */
{
    char_u	*p;
    int		c;
    int		len;
    int		capflags = mip->mi_capflags;	    /* flags of checked word */
    int		past_second;

    if ((capflags & BWF_KEEPCAP) == 0 && end > mip->mi_end)
    {
	/* If "end" is past "mip->mi_end" we need to check the characters
	 * after the basic word. */
#ifdef FEAT_MBYTE
	past_second = (mip->mi_word + (*mb_ptr2len_check)(mip->mi_word)
							       < mip->mi_end);
#else
	past_second = mip->mi_word + 1 < mip->mi_end;
#endif
	for (p = mip->mi_end; p < end; )
	{
	    if (!spell_iswordc(p))
		mb_ptr_adv(p);
	    else
	    {
#ifdef FEAT_MBYTE
		if (has_mbyte)
		    c = mb_ptr2char_adv(&p);
		else
#endif
		    c = *p++;
		if (MB_ISUPPER(c))
		{
		    if (capflags == 0 || (capflags & BWF_ONECAP))
		    {
			capflags = BWF_KEEPCAP;	/* lU or UlU */
			break;
		    }
		}
		else
		{
		    if (capflags & BWF_ALLCAP)
		    {
			if (past_second)
			{
			    capflags = BWF_KEEPCAP;	/* UUl */
			    break;
			}
			capflags = BWF_ONECAP;		/* Uu */
		    }
		}
		past_second = TRUE;
	    }
	}
    }

    if (capflags == BWF_ALLCAP)
	return TRUE;		/* All caps is always OK. */

    if (flags & BWF_KEEPCAP)
    {
	len = STRLEN(caseword);
	return (len == end - cword && STRNCMP(caseword, cword, len) == 0);
    }

    if (flags & BWF_ALLCAP)
	return FALSE;		/* need ALLCAP, already checked above */

    if (flags & BWF_ONECAP)
	return capflags == BWF_ONECAP;

    return capflags != BWF_KEEPCAP;	/* no case check, only KEEPCAP is bad */
}

/*
 * Move to next spell error.
 * Return OK if found, FAIL otherwise.
 */
    int
spell_move_to(dir, allwords)
    int		dir;		/* FORWARD or BACKWARD */
    int		allwords;	/* TRUE for "[s" and "]s" */
{
    pos_T	pos;
    char_u	*line;
    char_u	*p;
    int		wc;
    int		nwc;
    int		attr = 0;
    int		len;

    if (!curwin->w_p_spell || *curwin->w_buffer->b_p_spl == NUL)
    {
	EMSG(_("E756: Spell checking not enabled"));
	return FAIL;
    }

    /* TODO: moving backwards */

    /* Start looking for bad word at the start of the line, because we can't
     * start halfway a word and know where it ends. */
    pos = curwin->w_cursor;
    pos.col = 0;
    wc = FALSE;

    while (!got_int)
    {
	line = ml_get(pos.lnum);
	p = line + pos.col;
	while (*p != NUL)
	{
	    nwc = spell_iswordc(p);
	    if (!wc && nwc)
	    {
		/* start of word */
		/* TODO: check for bad word attr */
		len = spell_check(curwin, line, p, &attr);
		if (attr != 0)
		{
		    if (curwin->w_cursor.lnum < pos.lnum
			    || (curwin->w_cursor.lnum == pos.lnum
				&& curwin->w_cursor.col < (colnr_T)(p - line)))
		    {
			curwin->w_cursor.lnum = pos.lnum;
			curwin->w_cursor.col = p - line;
			return OK;
		    }
		    attr = 0;	/* bad word is before or at cursor */
		}
		p += len;
		if (*p == NUL)
		    break;
		nwc = FALSE;
	    }

	    /* advance to next character */
	    mb_ptr_adv(p);
	    wc = nwc;
	}

	/* Advance to next line. */
	if (pos.lnum == curbuf->b_ml.ml_line_count)
	    return FAIL;
	++pos.lnum;
	pos.col = 0;
	wc = FALSE;

	line_breakcheck();
    }

    return FAIL;	/* interrupted */
}

/*
 * Load word list for "lang" from a Vim spell file.
 * "lang" must be the language without the region: "en" or "en-rare".
 */
    static slang_T *
spell_load_lang(lang)
    char_u	*lang;
{
    slang_T	*lp;
    char_u	fname_enc[80];
    char_u	*p;
    int		r;

    lp = slang_alloc(lang);
    if (lp != NULL)
    {
	/* Find all spell files for "lang" in 'runtimepath' and load them.
	 * Use 'encoding', except that we use "latin1" for "latin9". */
#ifdef FEAT_MBYTE
	if (STRLEN(p_enc) < 60 && STRCMP(p_enc, "iso-8859-15") != 0)
	    p = p_enc;
	else
#endif
	    p = (char_u *)"latin1";
	sprintf((char *)fname_enc, "spell/%s.%s.spl", lang, p);

	r = do_in_runtimepath(fname_enc, TRUE, spell_load_file, lp);
	if (r == FAIL || lp->sl_error)
	{
	    slang_free(lp);
	    lp = NULL;
	    if (r == FAIL)
		smsg((char_u *)_("Warning: Cannot find word list \"%s\""),
							       fname_enc + 6);
	}
	else
	{
	    lp->sl_next = first_lang;
	    first_lang = lp;
	}
    }

    return lp;
}

/*
 * Allocate a new slang_T.
 * Caller must fill "sl_next".
 */
    static slang_T *
slang_alloc(lang)
    char_u	*lang;
{
    slang_T *lp;

    lp = (slang_T *)alloc(sizeof(slang_T));
    if (lp != NULL)
    {
	lp->sl_name = vim_strsave(lang);
	hash_init(&lp->sl_words);
	ga_init2(&lp->sl_preftab, sizeof(hashtab_T), 4);
	ga_init2(&lp->sl_sufftab, sizeof(hashtab_T), 4);
	lp->sl_prefzero = NULL;
	lp->sl_suffzero = NULL;
	lp->sl_try = NULL;
	ga_init2(&lp->sl_rep, sizeof(repentry_T), 4);
	lp->sl_regions[0] = NUL;
	lp->sl_block = NULL;
	lp->sl_error = FALSE;
    }
    return lp;
}

/*
 * Free the contents of an slang_T and the structure itself.
 */
    static void
slang_free(lp)
    slang_T	*lp;
{
    sblock_T	*sp;
    int		i;

    vim_free(lp->sl_name);
    hash_clear(&lp->sl_words);
    for (i = 0; i < lp->sl_preftab.ga_len; ++i)
	hash_clear(((hashtab_T *)lp->sl_preftab.ga_data) + i);
    ga_clear(&lp->sl_preftab);
    for (i = 0; i < lp->sl_sufftab.ga_len; ++i)
	hash_clear(((hashtab_T *)lp->sl_sufftab.ga_data) + i);
    ga_clear(&lp->sl_sufftab);
    ga_clear(&lp->sl_rep);
    vim_free(lp->sl_try);
    while (lp->sl_block != NULL)
    {
	sp = lp->sl_block;
	lp->sl_block = sp->sb_next;
	vim_free(sp);
    }
    vim_free(lp);
}

/*
 * Load one spell file into an slang_T.
 * Invoked through do_in_runtimepath().
 */
    static void
spell_load_file(fname, cookie)
    char_u	*fname;
    void	*cookie;	    /* points to the slang_T to be filled */
{
    slang_T	*lp = cookie;
    FILE	*fd;
    char_u	buf[MAXWLEN + 1];
    char_u	cbuf[MAXWLEN + 1];
    char_u	fbuf[MAXWLEN + 1];
    char_u	*p;
    int		itm;
    int		i;
    int		affcount;
    int		affnr;
    int		affflags;
    int		affitemcnt;
    int		bl_used = SBLOCKSIZE;
    int		widx;
    int		prefm;	    /* 1 if <= 256 prefixes, sizeof(short_u) otherw. */
    int		suffm;	    /* 1 if <= 256 suffixes, sizeof(short_u) otherw. */
    int		wlen;
    int		flags;
    affitem_T	*ai, *ai2, **aip;
    int		round;
    char_u	*save_sourcing_name = sourcing_name;
    linenr_T	save_sourcing_lnum = sourcing_lnum;
    int		cnt;
    int		choplen;
    int		addlen;
    int		leadlen;
    int		wordcount;
    fword_T	*fw, *fw2;
    garray_T	*gap;
    hashtab_T	*ht;
    hashitem_T	*hi;
    hash_T	hash;
    int		adds;
    addword_T	*aw;
    int		flen;

    fd = fopen((char *)fname, "r");
    if (fd == NULL)
    {
	EMSG2(_(e_notopen), fname);
	goto errorend;
    }

    /* Set sourcing_name, so that error messages mention the file name. */
    sourcing_name = fname;
    sourcing_lnum = 0;

    /* <HEADER>: <fileID> <regioncnt> <regionname> ... */
    for (i = 0; i < VIMSPELLMAGICL; ++i)
	buf[i] = getc(fd);				/* <fileID> */
    if (STRNCMP(buf, VIMSPELLMAGIC, VIMSPELLMAGICL) != 0)
    {
	EMSG(_("E757: Wrong file ID in spell file"));
	goto errorend;
    }

    cnt = getc(fd);					/* <regioncnt> */
    if (cnt == EOF)
    {
truncerr:
	EMSG(_("E758: Truncated spell file"));
	goto errorend;
    }
    if (cnt > 8)
    {
formerr:
	EMSG(_("E759: Format error in spell file"));
	goto errorend;
    }
    for (i = 0; i < cnt; ++i)
    {
	lp->sl_regions[i * 2] = getc(fd);		/* <regionname> */
	lp->sl_regions[i * 2 + 1] = getc(fd);
    }
    lp->sl_regions[cnt * 2] = NUL;

    /* round 1: <PREFIXLIST>: <affcount> <afftotcnt> <affix> ...
     * round 2: <SUFFIXLIST>: <affcount> <afftotcnt> <affix> ...  */
    for (round = 1; round <= 2; ++round)
    {
	affcount = (getc(fd) << 8) + getc(fd);		/* <affcount> */
	if (affcount < 0)
	    goto truncerr;
	if (round == 1)
	{
	    gap = &lp->sl_preftab;
	    aip = &lp->sl_prefzero;
	    lp->sl_prefcnt = affcount;
	    prefm = affcount > 256 ? sizeof(short_u) : 1;
	}
	else
	{
	    gap = &lp->sl_sufftab;
	    aip = &lp->sl_suffzero;
	    lp->sl_suffcnt = affcount;
	    suffm = affcount > 256 ? sizeof(short_u) : 1;
	}

	i = (getc(fd) << 8) + getc(fd);		/* <afftotcnt> */
	/* afftotcnt is not used */

	/*
	 * For each affix NR there can be several affixes.
	 */
	for (affnr = 0; affnr < affcount; ++affnr)
	{
	    /* <affix>: <affflags> <affitemcnt> <affitem> ... */
	    affflags = getc(fd);			/* <affflags> */
	    if (affflags == EOF)
		goto truncerr;
	    affitemcnt = (getc(fd) << 8) + getc(fd);	/* <affitemcnt> */
	    if (affitemcnt < 0)
		goto truncerr;
	    for (itm = 0; itm < affitemcnt; ++itm)
	    {
		/* <affitem>: <affchoplen> <affchop> <affaddlen> <affadd> */
		choplen = getc(fd);			/* <affchoplen> */
		if (choplen == EOF)
		    goto truncerr;
		if (choplen >= MAXWLEN)
		    goto formerr;
		for (i = 0; i < choplen; ++i)		/* <affchop> */
		    buf[i] = getc(fd);
		buf[i] = NUL;
		addlen = getc(fd);			/* <affaddlen> */
		if (addlen == EOF)
		    goto truncerr;
		/* Get room to store the affitem_T, chop and add strings. */
		p = (char_u *)getroom(lp, &bl_used,
				    sizeof(affitem_T) + choplen + addlen + 1);
		if (p == NULL)
		    goto errorend;

		ai = (affitem_T *)p;
		ai->ai_nr = affnr;
		ai->ai_combine = affflags;
		ai->ai_choplen = choplen;
		ai->ai_addlen = addlen;

		p += sizeof(affitem_T) + addlen;
		ai->ai_chop = p;
		STRCPY(p, buf);

		p = ai->ai_add;
		for (i = 0; i < addlen; ++i)		/* <affadd> */
		    p[i] = getc(fd);
		p[i] = NUL;

		/*
		 * Add the affix to a hashtable.  Which one depends on the
		 * length of the added string in characters.
		 */
#ifdef FEAT_MBYTE
		/* Change "addlen" from length in bytes to length in chars. */
		if (has_mbyte)
		    addlen = mb_charlen(p);
#endif
		if (addlen == 0)
		{
		    /* Link in list of zero length affixes. */
		    ai->ai_next = *aip;
		    *aip = ai;
		}
		else
		{
		    if (gap->ga_len < addlen)
		    {
			/* Longer affix, need more hashtables. */
			if (ga_grow(gap, addlen - gap->ga_len) == FAIL)
			    goto errorend;

			/* Re-allocating ga_data means that an ht_array
			 * pointing to ht_smallarray becomes invalid.  We can
			 * recognize this: ht_mask is at its init value. */
			for (i = 0; i < gap->ga_len; ++i)
			{
			    ht = ((hashtab_T *)gap->ga_data) + i;
			    if (ht->ht_mask == HT_INIT_SIZE - 1)
				ht->ht_array = ht->ht_smallarray;
			}

			/* Init the newly used hashtable(s). */
			while (gap->ga_len < addlen)
			{
			    hash_init(((hashtab_T *)gap->ga_data)
							       + gap->ga_len);
			    ++gap->ga_len;
			}
		    }
		    ht = ((hashtab_T *)gap->ga_data) + addlen - 1;
		    hash = hash_hash(p);
		    hi = hash_lookup(ht, p, hash);
		    if (HASHITEM_EMPTY(hi))
		    {
			/* First affix with this "ai_add", add to hashtable. */
			hash_add_item(ht, hi, p, hash);
			ai->ai_next = NULL;
		    }
		    else
		    {
			/* There already is an affix with this "ai_add", link
			 * in the list.  */
			ai2 = HI2AI(hi);
			ai->ai_next = ai2->ai_next;
			ai2->ai_next = ai;
		    }
		}
	    }
	}
    }

    /* <SUGGEST> : <suggestlen> <more> ... */
    /* TODO, just skip this for now */
    i = (getc(fd) << 24) + (getc(fd) << 16) + (getc(fd) << 8) + getc(fd);
    while (i-- > 0)
	if (getc(fd) == EOF)				/* <suggestlen> */
	    goto truncerr;

    /* <WORDLIST>: <wordcount> <worditem> ... */	/* <wordcount> */
    wordcount = (getc(fd) << 24) + (getc(fd) << 16) + (getc(fd) << 8)
								   + getc(fd);
    if (wordcount < 0)
	goto truncerr;

    /* Init hashtable for this number of words, so that it doesn't need to
     * reallocate the table halfway. */
    hash_lock_size(&lp->sl_words, wordcount);

    for (widx = 0; ; ++widx)
    {
	/* <worditem>: <nr> <string> <flags> [<flags2>]
	 *			  [<caselen> <caseword>]
	 *			  [<affixcnt> <affixNR> ...]    (prefixes)
	 *			  [<affixcnt> <affixNR> ...]	(suffixes)
	 *			  [<region>]
	 *			  [<addcnt> <add> ...]
	 */
	/* Use <nr> bytes from the previous word. */
	wlen = getc(fd);				/* <nr> */
	if (wlen == EOF)
	{
	    if (widx >= wordcount)	/* normal way to end the file */
		break;
	    goto truncerr;
	}

	/* Read further word bytes until one below 0x20, that must be the
	 * flags.  Keep this fast! */
	for (;;)
	{
	    if ((buf[wlen] = getc(fd)) < 0x20)		/* <string> */
		break;
	    if (++wlen == MAXWLEN)
		goto formerr;
	}
	flags = buf[wlen];				/* <flags> */
	buf[wlen] = NUL;

	/* Get more flags if they're there. */
	if (flags & BWF_SECOND)
	    flags += getc(fd) << 8;			/* <flags2> */

	if (flags & BWF_KEEPCAP)
	{
	    /* Read <caselen> and <caseword> first, its length may differ from
	     * the case-folded word.  Note: this should only happen after the
	     * basic word! */
	    wlen = getc(fd);
	    if (wlen == EOF)
		goto truncerr;
	    for (i = 0; i < wlen; ++i)
		cbuf[i] = getc(fd);
	    cbuf[i] = NUL;
	}

	/* Find room to store the word in a fword_T. */
	fw = (fword_T *)getroom(lp, &bl_used, (int)sizeof(fword_T) + wlen);
	if (fw == NULL)
	    goto errorend;
	mch_memmove(fw->fw_word, (flags & BWF_KEEPCAP) ? cbuf : buf, wlen + 1);
	fw->fw_flags = flags;

	hash = hash_hash(buf);
	hi = hash_lookup(&lp->sl_words, buf, hash);
	if (HASHITEM_EMPTY(hi))
	{
	    if (hash_add_item(&lp->sl_words, hi, fw->fw_word, hash) == FAIL)
		goto errorend;
	    fw->fw_next = NULL;
	}
	else
	{
	    /* Already have this basic word in the hashtable, this one will
	     * have different case flags. */
	    fw2 = HI2FWORD(hi);
	    fw->fw_next = fw2->fw_next;
	    fw2->fw_next = fw;
	    --widx;			/* don't count this one */
	}

	/* Optional prefixes and suffixes. */
	if (flags & BWF_PREFIX)
	    fw->fw_prefixcnt = spell_load_affixes(fd, lp, &bl_used,
						       prefm, &fw->fw_prefix);
	else
	    fw->fw_prefixcnt = 0;
	if (flags & BWF_SUFFIX)
	    fw->fw_suffixcnt = spell_load_affixes(fd, lp, &bl_used,
						       suffm, &fw->fw_suffix);
	else
	    fw->fw_suffixcnt = 0;

	if (flags & BWF_REGION)
	    fw->fw_region = getc(fd);			/* <region> */
	else
	    fw->fw_region = REGION_ALL;

	fw->fw_adds = NULL;
	if (flags & BWF_ADDS)
	{
	    adds = (getc(fd) << 8) + getc(fd);		/* <addcnt> */

	    while (--adds >= 0)
	    {
		/* <add>: <addflags> <addlen> [<leadlen> <addstring>]
		 *			[<region>] */
		flags = getc(fd);			/* <addflags> */
		addlen = getc(fd);			/* <addlen> */
		if (addlen == EOF)
		    goto truncerr;
		if (addlen >= MAXWLEN)
		    goto formerr;

		if (addlen > 0)
		{
		    leadlen = getc(fd);			/* <leadlen> */
		    for (i = 0; i < addlen; ++i)	/* <addstring> */
			cbuf[i] = getc(fd);
		    cbuf[i] = NUL;
		}
		else
		    leadlen = 0;

		if (flags & ADD_KEEPCAP)
		{
		    /* <addstring> is in original case, need to get
		     * case-folded word too. */
		    (void)str_foldcase(cbuf, addlen, fbuf, MAXWLEN);
		    flen = addlen - leadlen + 1;
		    addlen = STRLEN(fbuf);
		}
		else
		    flen = 0;

		aw = (addword_T *)getroom(lp, &bl_used,
					   sizeof(addword_T) + addlen + flen);
		if (aw == NULL)
		    goto errorend;
		aw->aw_next = fw->fw_adds;
		fw->fw_adds = aw;
		aw->aw_leadlen = leadlen;

		if (flags & ADD_KEEPCAP)
		{
		    /* Put the addition in original case after the case-folded
		     * string. */
		    STRCPY(aw->aw_word, fbuf);
		    STRCPY(aw->aw_word + addlen + 1, cbuf + leadlen);
		}
		else
		    STRCPY(aw->aw_word, cbuf);

		aw->aw_flags = flags;
		aw->aw_wordlen = addlen;

		if (flags & ADD_REGION)
		    aw->aw_region = getc(fd);		/* <region> */
		else
		    aw->aw_region = REGION_ALL;
	    }
	}
    }
    goto end_OK;

errorend:
    lp->sl_error = TRUE;
end_OK:
    if (fd != NULL)
	fclose(fd);
    hash_unlock(&lp->sl_words);
    sourcing_name = save_sourcing_name;
    sourcing_lnum = save_sourcing_lnum;
}

/*
 * Read a list of affixes from the spell file.
 */
    static int
spell_load_affixes(fd, lp, bl_usedp, affm, affp)
    FILE	*fd;
    slang_T	*lp;
    int		*bl_usedp;
    int		affm;
    void	**affp;
{
    int		cnt;
    int		i, n;
    char_u	*p;

    cnt = getc(fd);				/* <affixcnt> */
    if (cnt == EOF)
	return 0;

    /* Get room to store the affixNR list, either as char_u (1
     * byte) or short_u (2 bytes). */
    p = (char_u *)getroom(lp, bl_usedp, cnt * affm);
    if (p == NULL)
	return 0;
    *affp = p;
    for (n = 0; n < cnt; ++n)
    {
	i = getc(fd);			/* <affixNR> */
	if (affm > 1)
	{
	    i = (i << 8) + getc(fd);
	    *(short_u *)p = i;
	    p += sizeof(short_u);
	}
	else
	{
	    *(char_u *)p = i;
	    ++p;
	}
    }
    return cnt;
}

/*
 * Get part of an sblock_T, at least "len" bytes long.
 * Returns NULL when out of memory.
 */
    static void *
getroom(lp, bl_used, len)
    slang_T	*lp;	    /* lp->sl_block is current block or NULL */
    int		*bl_used;    /* used up from current block */
    int		len;	    /* length needed */
{
    char_u	*p;
    sblock_T	*bl = lp->sl_block;

    if (bl == NULL || *bl_used + len > SBLOCKSIZE)
    {
	/* Allocate a block of memory. This is not freed until spell_reload()
	 * is called. */
	bl = (sblock_T *)alloc((unsigned)(sizeof(sblock_T) + SBLOCKSIZE));
	if (bl == NULL)
	    return NULL;
	bl->sb_next = lp->sl_block;
	lp->sl_block = bl;
	*bl_used = 0;
    }

    p = bl->sb_data + *bl_used;
    *bl_used += len;

    return p;
}

/*
 * Parse 'spelllang' and set buf->b_langp accordingly.
 * Returns an error message or NULL.
 */
    char_u *
did_set_spelllang(buf)
    buf_T	*buf;
{
    garray_T	ga;
    char_u	*lang;
    char_u	*e;
    char_u	*region;
    int		region_mask;
    slang_T	*lp;
    int		c;
    char_u	lbuf[MAXWLEN + 1];

    ga_init2(&ga, sizeof(langp_T), 2);

    /* loop over comma separated languages. */
    for (lang = buf->b_p_spl; *lang != NUL; lang = e)
    {
	e = vim_strchr(lang, ',');
	if (e == NULL)
	    e = lang + STRLEN(lang);
	if (e > lang + 2)
	{
	    if (e - lang >= MAXWLEN)
	    {
		ga_clear(&ga);
		return e_invarg;
	    }
	    if (lang[2] == '_')
		region = lang + 3;
	}
	else
	    region = NULL;

	for (lp = first_lang; lp != NULL; lp = lp->sl_next)
	    if (STRNICMP(lp->sl_name, lang, 2) == 0)
		break;

	if (lp == NULL)
	{
	    /* Not found, load the language. */
	    STRNCPY(lbuf, lang, e - lang);
	    lbuf[e - lang] = NUL;
	    if (region != NULL)
		mch_memmove(lbuf + 2, lbuf + 5, e - lang - 4);
	    lp = spell_load_lang(lbuf);
	}

	if (lp != NULL)
	{
	    if (region == NULL)
		region_mask = REGION_ALL;
	    else
	    {
		/* find region in sl_regions */
		c = find_region(lp->sl_regions, region);
		if (c == REGION_ALL)
		{
		    c = *e;
		    *e = NUL;
		    smsg((char_u *)_("Warning: region %s not supported"), lang);
		    *e = c;
		    region_mask = REGION_ALL;
		}
		else
		    region_mask = 1 << c;
	    }

	    if (ga_grow(&ga, 1) == FAIL)
	    {
		ga_clear(&ga);
		return e_outofmem;
	    }
	    LANGP_ENTRY(ga, ga.ga_len)->lp_slang = lp;
	    LANGP_ENTRY(ga, ga.ga_len)->lp_region = region_mask;
	    ++ga.ga_len;
	}

	if (*e == ',')
	    ++e;
    }

    /* Add a NULL entry to mark the end of the list. */
    if (ga_grow(&ga, 1) == FAIL)
    {
	ga_clear(&ga);
	return e_outofmem;
    }
    LANGP_ENTRY(ga, ga.ga_len)->lp_slang = NULL;
    ++ga.ga_len;

    /* Everything is fine, store the new b_langp value. */
    ga_clear(&buf->b_langp);
    buf->b_langp = ga;

    return NULL;
}

/*
 * Find the region "region[2]" in "rp" (points to "sl_regions").
 * Each region is simply stored as the two characters of it's name.
 * Returns the index if found, REGION_ALL if not found.
 */
    static int
find_region(rp, region)
    char_u	*rp;
    char_u	*region;
{
    int		i;

    for (i = 0; ; i += 2)
    {
	if (rp[i] == NUL)
	    return REGION_ALL;
	if (rp[i] == region[0] && rp[i + 1] == region[1])
	    break;
    }
    return i / 2;
}

/*
 * Return type of word:
 * w word	0
 * Word		BWF_ONECAP
 * W WORD	BWF_ALLCAP
 * WoRd	wOrd	BWF_KEEPCAP
 */
    static int
captype(word, end)
    char_u	*word;
    char_u	*end;
{
    char_u	*p;
    int		c;
    int		firstcap;
    int		allcap;
    int		past_second = FALSE;	/* past second word char */

    /* find first letter */
    for (p = word; !spell_iswordc(p); mb_ptr_adv(p))
	if (p >= end)
	    return 0;	    /* only non-word characters, illegal word */
#ifdef FEAT_MBYTE
    c = mb_ptr2char_adv(&p);
#else
    c = *p++;
#endif
    firstcap = allcap = MB_ISUPPER(c);

    /*
     * Need to check all letters to find a word with mixed upper/lower.
     * But a word with an upper char only at start is a ONECAP.
     */
    for ( ; p < end; mb_ptr_adv(p))
	if (spell_iswordc(p))
	{
#ifdef FEAT_MBYTE
	    c = mb_ptr2char(p);
#else
	    c = *p;
#endif
	    if (!MB_ISUPPER(c))
	    {
		/* UUl -> KEEPCAP */
		if (past_second && allcap)
		    return BWF_KEEPCAP;
		allcap = FALSE;
	    }
	    else if (!allcap)
		/* UlU -> KEEPCAP */
		return BWF_KEEPCAP;
	    past_second = TRUE;
	}

    if (allcap)
	return BWF_ALLCAP;
    if (firstcap)
	return BWF_ONECAP;
    return 0;
}

# if defined(FEAT_MBYTE) || defined(PROTO)
/*
 * Clear all spelling tables and reload them.
 * Used after 'encoding' is set.
 */
    void
spell_reload()
{
    buf_T	*buf;
    slang_T	*lp;

    /* Initialize the table for spell_iswordc(). */
    init_spell_chartab();

    /* Unload all allocated memory. */
    while (first_lang != NULL)
    {
	lp = first_lang;
	first_lang = lp->sl_next;
	slang_free(lp);
    }

    /* Go through all buffers and handle 'spelllang'. */
    for (buf = firstbuf; buf != NULL; buf = buf->b_next)
    {
	ga_clear(&buf->b_langp);
	if (*buf->b_p_spl != NUL)
	    did_set_spelllang(buf);
    }
}
# endif

/*
 * Recognizing words uses a two-step mechanism:
 * 1. Locate a basic word, made out of word characters only and separated by
 *    non-word characters.
 * 2. When a basic word is found, check if (possibly required) additions
 *    before and after the word are present.
 *
 * Both mechanisms use affixes (prefixes and suffixes) to reduce the number of
 * words.  When no matching word was found in the hashtable the start of the
 * word is checked for matching prefixes and the end of the word for matching
 * suffixes.  All matching affixes are removed and then the resulting word is
 * searched for.  If found it is checked if it supports the used affix.
 */


#if defined(FEAT_MBYTE) || defined(PROTO)
/*
 * Functions for ":mkspell".
 * Only possible with the multi-byte feature.
 */

#define MAXLINELEN  300		/* Maximum length in bytes of a line in a .aff
				   and .dic file. */
/*
 * Main structure to store the contents of a ".aff" file.
 */
typedef struct afffile_S
{
    char_u	*af_enc;	/* "SET", normalized, alloc'ed string or NULL */
    char_u	*af_try;	/* "TRY" line in "af_enc" encoding */
    hashtab_T	af_pref;	/* hashtable for prefixes, affheader_T */
    hashtab_T	af_suff;	/* hashtable for suffixes, affheader_T */
    garray_T	af_rep;		/* list of repentry_T entries from REP lines */
} afffile_T;

typedef struct affentry_S affentry_T;

/* Affix header from ".aff" file.  Used for af_pref and af_suff. */
typedef struct affheader_S
{
    char_u	ah_key[2];	/* key for hashtable == name of affix entry */
    int		ah_combine;
    affentry_T	*ah_first;	/* first affix entry */
    short_u	ah_affnr;	/* used in get_new_aff() */
} affheader_T;

#define HI2AH(hi)   ((affheader_T *)(hi)->hi_key)

/* Affix entry from ".aff" file.  Used for prefixes and suffixes. */
struct affentry_S
{
    affentry_T	*ae_next;	/* next affix with same name/number */
    char_u	*ae_chop;	/* text to chop off basic word (can be NULL) */
    char_u	*ae_add;	/* text to add to basic word (can be NULL) */
    char_u	*ae_add_nw;	/* first non-word character in "ae_add" */
    char_u	*ae_cond;	/* condition (NULL for ".") */
    regprog_T	*ae_prog;	/* regexp program for ae_cond or NULL */
    short_u	ae_affnr;	/* for old affix: new affix number */
};

/*
 * Structure to store a word from a ".dic" file.
 */
typedef struct dicword_S
{
    char_u	*dw_affnm;	/* original affix names */
    char_u	dw_word[1];	/* actually longer: the word in 'encoding' */
} dicword_T;

static dicword_T dumdw;
#define HI2DW(hi)	((dicword_T *)((hi)->hi_key - (dumdw.dw_word - (char_u *)&dumdw)))

/*
 * Structure to store a basic word for the spell file.
 * This is used for ":mkspell", not for spell checking.
 */
typedef struct basicword_S basicword_T;
struct basicword_S
{
    basicword_T	*bw_next;	/* next word with same basic word */
    basicword_T	*bw_cnext;	/* next word with same caps */
    int		bw_flags;	/* BWF_ flags */
    garray_T	bw_prefix;	/* table with prefix numbers */
    garray_T	bw_suffix;	/* table with suffix numbers */
    int		bw_region;	/* region bits */
    char_u	*bw_caseword;	/* keep-case word */
    char_u	*bw_leadstring;	/* must come before bw_word */
    char_u	*bw_addstring;	/* must come after bw_word */
    char_u	bw_word[1];	/* actually longer: word case folded */
};

static basicword_T dumbw;
#define KEY2BW(p)	((basicword_T *)((p) - (dumbw.bw_word - (char_u *)&dumbw)))
#define HI2BW(hi)	KEY2BW((hi)->hi_key)

/* Store the affix number related with a certain string. */
typedef struct affhash_S
{
    short_u	as_nr;		/* the affix nr */
    char_u	as_word[1];	/* actually longer */
} affhash_T;

static affhash_T dumas;
#define HI2AS(hi)	((affhash_T *)((hi)->hi_key - (dumas.as_word - (char_u *)&dumas)))


static afffile_T *spell_read_aff __ARGS((char_u *fname, vimconv_T *conv));
static void spell_free_aff __ARGS((afffile_T *aff));
static int spell_read_dic __ARGS((hashtab_T *ht, char_u *fname, vimconv_T *conv));
static int get_new_aff __ARGS((hashtab_T *oldaff, garray_T *gap));
static void spell_free_dic __ARGS((hashtab_T *dic));
static int same_affentries __ARGS((affheader_T *ah1, affheader_T *ah2));
static void add_affhash __ARGS((hashtab_T *ht, char_u *key, int newnr));
static void clear_affhash __ARGS((hashtab_T *ht));
static void trans_affixes __ARGS((dicword_T *dw, basicword_T *bw, afffile_T *oldaff, hashtab_T *newwords));
static int build_wordlist __ARGS((hashtab_T *newwords, hashtab_T *oldwords, afffile_T *oldaff, int regionmask));
static void combine_regions __ARGS((hashtab_T *newwords));
static int same_affixes __ARGS((basicword_T *bw, basicword_T *nbw));
static void expand_affixes __ARGS((hashtab_T *newwords, garray_T *prefgap, garray_T *suffgap));
static void expand_one_aff __ARGS((basicword_T *bw, garray_T *add_words, affentry_T *pae, affentry_T *sae));
static void add_to_wordlist __ARGS((hashtab_T *newwords, basicword_T *bw));
static void put_bytes __ARGS((FILE *fd, long_u nr, int len));
static void write_affix __ARGS((FILE *fd, affheader_T *ah));
static void write_affixlist __ARGS((FILE *fd, garray_T *aff, int bytes));
static void write_vim_spell __ARGS((char_u *fname, garray_T *prefga, garray_T *suffga, hashtab_T *newwords, int regcount, char_u *regchars));
static void write_bword __ARGS((FILE *fd, basicword_T *bw, int lowcap, basicword_T **prevbw, int regionmask, int prefm, int suffm));
static void free_wordtable __ARGS((hashtab_T *ht));
static void free_basicword __ARGS((basicword_T *bw));
static void free_affixentries __ARGS((affentry_T *first));

/*
 * Read an affix ".aff" file.
 * Returns an afffile_T, NULL for failure.
 */
    static afffile_T *
spell_read_aff(fname, conv)
    char_u	*fname;
    vimconv_T	*conv;		/* info for encoding conversion */
{
    FILE	*fd;
    afffile_T	*aff;
    char_u	rline[MAXLINELEN];
    char_u	*line;
    char_u	*pc = NULL;
    char_u	*(items[6]);
    int		itemcnt;
    char_u	*p;
    int		lnum = 0;
    affheader_T	*cur_aff = NULL;
    int		aff_todo = 0;
    hashtab_T	*tp;

    fd = fopen((char *)fname, "r");
    if (fd == NULL)
    {
	EMSG2(_(e_notopen), fname);
	return NULL;
    }

    smsg((char_u *)_("Reading affix file %s..."), fname);
    out_flush();

    aff = (afffile_T *)alloc_clear((unsigned)sizeof(afffile_T));
    if (aff == NULL)
	return NULL;
    hash_init(&aff->af_pref);
    hash_init(&aff->af_suff);
    ga_init2(&aff->af_rep, (int)sizeof(repentry_T), 20);

    /*
     * Read all the lines in the file one by one.
     */
    while (!vim_fgets(rline, MAXLINELEN, fd))
    {
	++lnum;

	/* Skip comment lines. */
	if (*rline == '#')
	    continue;

	/* Convert from "SET" to 'encoding' when needed. */
	vim_free(pc);
	if (conv->vc_type != CONV_NONE)
	{
	    pc = string_convert(conv, rline, NULL);
	    line = pc;
	}
	else
	{
	    pc = NULL;
	    line = rline;
	}

	/* Split the line up in white separated items.  Put a NUL after each
	 * item. */
	itemcnt = 0;
	for (p = line; ; )
	{
	    while (*p != NUL && *p <= ' ')  /* skip white space and CR/NL */
		++p;
	    if (*p == NUL)
		break;
	    items[itemcnt++] = p;
	    while (*p > ' ')  /* skip until white space or CR/NL */
		++p;
	    if (*p == NUL)
		break;
	    *p++ = NUL;
	}

	/* Handle non-empty lines. */
	if (itemcnt > 0)
	{
	    if (STRCMP(items[0], "SET") == 0 && itemcnt == 2
						       && aff->af_enc == NULL)
	    {
		if (aff->af_enc != NULL)
		    smsg((char_u *)_("Duplicate SET line ignored in %s line %d: %s"),
						       fname, lnum, line);
		else
		{
		    /* Setup for conversion from "ENC" to 'encoding'. */
		    aff->af_enc = enc_canonize(items[1]);
		    if (aff->af_enc != NULL
			    && convert_setup(conv, aff->af_enc, p_enc) == FAIL)
			smsg((char_u *)_("Conversion in %s not supported: from %s to %s"),
						   fname, aff->af_enc, p_enc);
		}
	    }
	    else if (STRCMP(items[0], "TRY") == 0 && itemcnt == 2
						       && aff->af_try == NULL)
		aff->af_try = vim_strsave(items[1]);
	    else if ((STRCMP(items[0], "PFX") == 0
					      || STRCMP(items[0], "SFX") == 0)
		    && aff_todo == 0
		    && itemcnt == 4)
	    {
		/* New affix letter. */
		cur_aff = (affheader_T *)alloc((unsigned)sizeof(affheader_T));
		if (cur_aff == NULL)
		    break;
		cur_aff->ah_key[0] = *items[1];
		cur_aff->ah_key[1] = NUL;
		if (items[1][1] != NUL)
		    smsg((char_u *)_("Affix name too long in %s line %d: %s"),
						       fname, lnum, items[1]);
		if (*items[2] == 'Y')
		    cur_aff->ah_combine = TRUE;
		else if (*items[2] == 'N')
		    cur_aff->ah_combine = FALSE;
		else if (p_verbose > 0)
		    smsg((char_u *)_("Expected Y or N in %s line %d: %s"),
						       fname, lnum, items[2]);
		cur_aff->ah_first = NULL;
		if (*items[0] == 'P')
		    tp = &aff->af_pref;
		else
		    tp = &aff->af_suff;
		if (!HASHITEM_EMPTY(hash_find(tp, cur_aff->ah_key)))
		    smsg((char_u *)_("Duplicate affix in %s line %d: %s"),
						       fname, lnum, items[1]);
		else
		    hash_add(tp, cur_aff->ah_key);

		aff_todo = atoi((char *)items[3]);
	    }
	    else if ((STRCMP(items[0], "PFX") == 0
					      || STRCMP(items[0], "SFX") == 0)
		    && aff_todo > 0
		    && STRCMP(cur_aff->ah_key, items[1]) == 0
		    && itemcnt == 5)
	    {
		affentry_T	*aff_entry;

		/* New item for an affix letter. */
		--aff_todo;
		aff_entry = (affentry_T *)alloc_clear(
						(unsigned)sizeof(affentry_T));
		if (aff_entry == NULL)
		    break;
		aff_entry->ae_next = cur_aff->ah_first;
		cur_aff->ah_first = aff_entry;
		if (STRCMP(items[2], "0") != 0)
		    aff_entry->ae_chop = vim_strsave(items[2]);
		if (STRCMP(items[3], "0") != 0)
		    aff_entry->ae_add = vim_strsave(items[3]);
		if (STRCMP(items[4], ".") != 0)
		{
		    char_u	buf[MAXLINELEN];

		    aff_entry->ae_cond = vim_strsave(items[4]);
		    if (*items[0] == 'P')
			sprintf((char *)buf, "^%s", items[4]);
		    else
			sprintf((char *)buf, "%s$", items[4]);
		    aff_entry->ae_prog = vim_regcomp(buf, RE_MAGIC + RE_STRING);
		}
	    }
	    else if (STRCMP(items[0], "REP") == 0 && itemcnt == 2)
		/* Ignore REP count */;
	    else if (STRCMP(items[0], "REP") == 0 && itemcnt == 3)
	    {
		repentry_T  *rp;

		/* REP item */
		if (ga_grow(&aff->af_rep, 1) == FAIL)
		    break;
		rp = ((repentry_T *)aff->af_rep.ga_data) + aff->af_rep.ga_len;
		rp->re_from = vim_strsave(items[1]);
		rp->re_to = vim_strsave(items[2]);
		++aff->af_rep.ga_len;
	    }
	    else if (p_verbose > 0)
		smsg((char_u *)_("Unrecognized item in %s line %d: %s"),
						       fname, lnum, items[0]);
	}

    }

    vim_free(pc);
    fclose(fd);
    return aff;
}

/*
 * Free the structure filled by spell_read_aff().
 */
    static void
spell_free_aff(aff)
    afffile_T	*aff;
{
    hashtab_T	*ht;
    hashitem_T	*hi;
    int		todo;
    int		i;
    repentry_T  *rp;
    affheader_T	*ah;

    vim_free(aff->af_enc);
    vim_free(aff->af_try);

    for (ht = &aff->af_pref; ; ht = &aff->af_suff)
    {
	todo = ht->ht_used;
	for (hi = ht->ht_array; todo > 0; ++hi)
	{
	    if (!HASHITEM_EMPTY(hi))
	    {
		--todo;
		ah = HI2AH(hi);
		free_affixentries(ah->ah_first);
		vim_free(ah);
	    }
	}
	if (ht == &aff->af_suff)
	    break;
    }
    hash_clear(&aff->af_pref);
    hash_clear(&aff->af_suff);

    for (i = 0; i < aff->af_rep.ga_len; ++i)
    {
	rp = ((repentry_T *)aff->af_rep.ga_data) + i;
	vim_free(rp->re_from);
	vim_free(rp->re_to);
    }
    ga_clear(&aff->af_rep);

    vim_free(aff);
}

/*
 * Read a dictionary ".dic" file.
 * Returns OK or FAIL;
 * Each entry in the hashtab_T is a dicword_T.
 */
    static int
spell_read_dic(ht, fname, conv)
    hashtab_T	*ht;
    char_u	*fname;
    vimconv_T	*conv;		/* info for encoding conversion */
{
    char_u	line[MAXLINELEN];
    char_u	*p;
    dicword_T	*dw;
    char_u	*pc;
    char_u	*w;
    int		l;
    hash_T	hash;
    hashitem_T	*hi;
    FILE	*fd;
    int		lnum = 1;

    fd = fopen((char *)fname, "r");
    if (fd == NULL)
    {
	EMSG2(_(e_notopen), fname);
	return FAIL;
    }

    smsg((char_u *)_("Reading dictionary file %s..."), fname);
    out_flush();

    /* Read and ignore the first line: word count. */
    (void)vim_fgets(line, MAXLINELEN, fd);
    if (!isdigit(*skipwhite(line)))
	EMSG2(_("E760: No word count in %s"), fname);

    /*
     * Read all the lines in the file one by one.
     * The words are converted to 'encoding' here, before being added to
     * the hashtable.
     */
    while (!vim_fgets(line, MAXLINELEN, fd))
    {
	++lnum;

	/* Remove CR, LF and white space from end. */
	l = STRLEN(line);
	while (l > 0 && line[l - 1] <= ' ')
	    --l;
	if (l == 0)
	    continue;	/* empty line */
	line[l] = NUL;

	/* Find the optional affix names. */
	p = vim_strchr(line, '/');
	if (p != NULL)
	    *p++ = NUL;

	/* Convert from "SET" to 'encoding' when needed. */
	if (conv->vc_type != CONV_NONE)
	{
	    pc = string_convert(conv, line, NULL);
	    w = pc;
	}
	else
	{
	    pc = NULL;
	    w = line;
	}

	dw = (dicword_T *)alloc_clear((unsigned)sizeof(dicword_T)
							     + STRLEN(w));
	if (dw == NULL)
	    break;
	STRCPY(dw->dw_word, w);
	vim_free(pc);

	hash = hash_hash(dw->dw_word);
	hi = hash_lookup(ht, dw->dw_word, hash);
	if (!HASHITEM_EMPTY(hi))
	    smsg((char_u *)_("Duplicate word in %s line %d: %s"),
						       fname, lnum, line);
	else
	    hash_add_item(ht, hi, dw->dw_word, hash);

	if (p != NULL)
	    dw->dw_affnm = vim_strsave(p);
    }

    fclose(fd);
    return OK;
}

/*
 * Free the structure filled by spell_read_dic().
 */
    static void
spell_free_dic(dic)
    hashtab_T	*dic;
{
    int		todo;
    dicword_T	*dw;
    hashitem_T	*hi;

    todo = dic->ht_used;
    for (hi = dic->ht_array; todo > 0; ++hi)
    {
	if (!HASHITEM_EMPTY(hi))
	{
	    --todo;
	    dw = HI2DW(hi);
	    vim_free(dw->dw_affnm);
	    vim_free(dw);
	}
    }
    hash_clear(dic);
}

/*
 * Take the affixes read by spell_read_aff() and add them to the new list.
 * Attempts to re-use the same number for identical affixes (ignoring the
 * condition, since we remove that).  That is especially important when using
 * multiple regions.
 * Returns OK or FAIL;
 */
    static int
get_new_aff(oldaff, gap)
    hashtab_T	*oldaff;	/* hashtable with affheader_T */
    garray_T	*gap;		/* table with new affixes */
{
    int		oldtodo;
    affheader_T	*oldah, *newah, *gapah;
    affentry_T	*oldae, *newae;
    hashitem_T	*oldhi;
    hashitem_T	*hi;
    hashtab_T	condht;		/* conditions already found */
    char_u	condkey[MAXLINELEN];
    int		newnr;
    int		gapnr;
    int		retval = OK;
    char_u	*p;
    garray_T	tga;

    /*
     * Loop over all the old affix names.
     */
    oldtodo = oldaff->ht_used;
    for (oldhi = oldaff->ht_array; oldtodo > 0 && retval == OK; ++oldhi)
    {
	if (!HASHITEM_EMPTY(oldhi))
	{
	    --oldtodo;
	    oldah = (affheader_T *)oldhi->hi_key;

	    /* Put entries with the same condition under the same new affix
	     * nr in "tga".  Use hashtable "condht" to find them. */
	    ga_init2(&tga, sizeof(affheader_T), 10);
	    hash_init(&condht);

	    /*
	     * Loop over all affixes with the same name.
	     * The affixes with the same condition will get the same number,
	     * since they can be used with the same words.
	     * 1. build the lists of new affentry_T, with the headers in "tga".
	     * 2. Check if some of the lists already exist in "gap", re-use
	     *    their number.
	     * 3. Assign the new numbers to the old affixes.
	     */

	    /* 1. build the lists of new affentry_T. */
	    for (oldae = oldah->ah_first; oldae != NULL && retval == OK;
						       oldae = oldae->ae_next)
	    {
		oldae->ae_add_nw = NULL;
		if (oldae->ae_add != NULL)
		{
		    /* Check for non-word characters in the suffix.  If there
		     * is one this affix will be turned into an addition.
		     * This is stored with the old affix, that is where
		     * trans_affixes() will check. */
		    for (p = oldae->ae_add; *p != NUL; mb_ptr_adv(p))
			if (!spell_iswordc(p))
			    break;
		    if (*p != NUL)
			oldae->ae_add_nw = p;
		}

		if (oldae->ae_cond == NULL)
		    /* hashtable requires a non-empty key */
		    STRCPY(condkey, "---");
		else
		    STRCPY(condkey, oldae->ae_cond);

		/* Look for an existing list with this name and condition. */
		hi = hash_find(&condht, condkey);
		if (!HASHITEM_EMPTY(hi))
		    /* Match with existing affix, use that one. */
		    newnr = HI2AS(hi)->as_nr;
		else
		{
		    /* Add a new affix number. */
		    newnr = tga.ga_len;
		    if (ga_grow(&tga, 1) == FAIL)
			retval = FAIL;
		    else
		    {
			newah = ((affheader_T *)tga.ga_data) + newnr;
			newah->ah_combine = oldah->ah_combine;
			newah->ah_first = NULL;
			++tga.ga_len;

			/* Add the new list to the condht hashtable. */
			add_affhash(&condht, condkey, newnr);
		    }
		}

		/* Add the new affentry_T to the list. */
		newah = ((affheader_T *)tga.ga_data) + newnr;
		newae = (affentry_T *)alloc_clear((unsigned)sizeof(affentry_T));
		if (newae == NULL)
		    retval = FAIL;
		else
		{
		    newae->ae_next = newah->ah_first;
		    newah->ah_first = newae;
		    if (oldae->ae_chop == NULL)
			newae->ae_chop = NULL;
		    else
			newae->ae_chop = vim_strsave(oldae->ae_chop);
		    if (oldae->ae_add == NULL)
			newae->ae_add = NULL;
		    else
			newae->ae_add = vim_strsave(oldae->ae_add);

		    /* The condition is not copied, since the new affix is
		     * only used for words where the condition matches. */
		}
	    }

	    /* 2. Check if some of the lists already exist, re-use their
	     *    number.  Otherwise add the list to "gap". */
	    for (newnr = 0; newnr < tga.ga_len; ++newnr)
	    {
		newah = ((affheader_T *)tga.ga_data) + newnr;
		for (gapnr = 0; gapnr < gap->ga_len; ++gapnr)
		{
		    gapah = ((affheader_T *)gap->ga_data) + gapnr;
		    if (same_affentries(newah, gapah))
			/* Found an existing affheader_T entry with same
			 * affentry_T list, use its number. */
			break;
		}

		newah->ah_affnr = gapnr;
		if (gapnr == gap->ga_len)
		{
		    /* This is a new affentry_T list, add it. */
		    if (ga_grow(gap, 1) == FAIL)
			retval = FAIL;
		    else
		    {
			*(((affheader_T *)gap->ga_data) + gap->ga_len) = *newah;
			++gap->ga_len;
		    }
		}
		else
		{
		    /* free unused affentry_T list */
		    free_affixentries(newah->ah_first);
		}
	    }

	    /* 3. Assign the new affix numbers to the old affixes. */
	    for (oldae = oldah->ah_first; oldae != NULL && retval == OK;
						       oldae = oldae->ae_next)
	    {
		if (oldae->ae_cond == NULL)
		    /* hashtable requires a non-empty key */
		    STRCPY(condkey, "---");
		else
		    STRCPY(condkey, oldae->ae_cond);

		/* Look for an existing affix with this name and condition. */
		hi = hash_find(&condht, condkey);
		if (!HASHITEM_EMPTY(hi))
		    /* Match with existing affix, use that one. */
		    newnr = HI2AS(hi)->as_nr;
		else
		{
		    EMSG(_(e_internal));
		    retval = FAIL;
		}
		newah = ((affheader_T *)tga.ga_data) + newnr;
		oldae->ae_affnr = newah->ah_affnr;
	    }

	    ga_clear(&tga);
	    clear_affhash(&condht);
	}
    }

    return retval;
}

/*
 * Return TRUE if the affentry_T lists for "ah1" and "ah2" contain the same
 * items, ignoring the order.
 * Only compares the chop and add strings, not the condition.
 */
    static int
same_affentries(ah1, ah2)
    affheader_T	*ah1;
    affheader_T	*ah2;
{
    affentry_T	*ae1, *ae2;

    /* Check the length of the lists first. */
    ae2 = ah2->ah_first;
    for (ae1 = ah1->ah_first; ae1 != NULL; ae1 = ae1->ae_next)
    {
	if (ae2 == NULL)
	    return FALSE;	/* "ah1" list is longer */
	ae2 = ae2->ae_next;
    }
    if (ae2 != NULL)
	return FALSE;		/* "ah2" list is longer */

    /* Check that each entry in "ah1" appears in "ah2". */
    for (ae1 = ah1->ah_first; ae1 != NULL; ae1 = ae1->ae_next)
    {
	for (ae2 = ah2->ah_first; ae2 != NULL; ae2 = ae2->ae_next)
	{
	    if ((ae1->ae_chop == NULL) == (ae2->ae_chop == NULL)
		&& (ae1->ae_add == NULL) == (ae2->ae_add == NULL)
		&& (ae1->ae_chop == NULL
				   || STRCMP(ae1->ae_chop, ae2->ae_chop) == 0)
		&& (ae1->ae_add == NULL
				    || STRCMP(ae1->ae_add, ae2->ae_add) == 0))
		break;
	}
	if (ae2 == NULL)
	    return FALSE;
    }

    return TRUE;
}

/*
 * Add a chop/add or cond hashtable entry.
 */
    static void
add_affhash(ht, key, newnr)
    hashtab_T	*ht;
    char_u	*key;
    int		newnr;
{
    affhash_T	*as;

    as = (affhash_T *)alloc((unsigned)sizeof(affhash_T) + STRLEN(key));
    if (as != NULL)
    {
	as->as_nr = newnr;
	STRCPY(as->as_word, key);
	hash_add(ht, as->as_word);
    }
}

/*
 * Clear the chop/add hashtable used to detect identical affixes.
 */
    static void
clear_affhash(ht)
    hashtab_T	*ht;
{
    int		todo;
    hashitem_T	*hi;

    todo = ht->ht_used;
    for (hi = ht->ht_array; todo > 0; ++hi)
    {
	if (!HASHITEM_EMPTY(hi))
	{
	    --todo;
	    vim_free(HI2AS(hi));
	}
    }
    hash_clear(ht);
}

/*
 * Translate list of affix names for an old word to affix numbers in a new
 * basic word.
 * This checks if the conditions match with the old word.  The result is that
 * the new affix does not need to store the condition.
 */
    static void
trans_affixes(dw, bw, oldaff, newwords)
    dicword_T	*dw;		/* old word */
    basicword_T *bw;		/* basic word */
    afffile_T	*oldaff;	/* affixes for "oldwords" */
    hashtab_T	*newwords;	/* table with words */
{
    char_u	key[2];
    char_u	*p;
    char_u	*affnm;
    garray_T	*gap;
    hashitem_T	*aff_hi;
    affheader_T	*ah;
    affentry_T	*ae;
    regmatch_T	regmatch;
    int		i;
    basicword_T *nbw;
    int		alen;
    int		wlen;
    garray_T	fixga;
    char_u	nword[MAXWLEN];
    int		flags;
    int		n;

    ga_init2(&fixga, (int)sizeof(basicword_T *), 5);

    /* Loop over all the affix names of the old word. */
    key[1] = NUL;
    for (affnm = dw->dw_affnm; *affnm != NUL; ++affnm)
    {
	key[0] = *affnm;
	aff_hi = hash_find(&oldaff->af_pref, key);
	if (!HASHITEM_EMPTY(aff_hi))
	    gap = &bw->bw_prefix;	/* found a prefix */
	else
	{
	    gap = &bw->bw_suffix;	/* must be a suffix */
	    aff_hi = hash_find(&oldaff->af_suff, key);
	    if (HASHITEM_EMPTY(aff_hi))
	    {
		smsg((char_u *)_("No affix entry '%s' for word %s"),
							    key, dw->dw_word);
		continue;
	    }
	}

	/* Loop over all the affix entries for this affix name. */
	ah = HI2AH(aff_hi);
	for (ae = ah->ah_first; ae != NULL; ae = ae->ae_next)
	{
	    regmatch.regprog = ae->ae_prog;
	    regmatch.rm_ic = FALSE;	/* TODO: Should this be TRUE??? */
	    if (ae->ae_prog == NULL
			   || vim_regexec(&regmatch, dw->dw_word, (colnr_T)0))
	    {
		if (ae->ae_add_nw != NULL && (gap == &bw->bw_suffix
			    ? bw->bw_addstring : bw->bw_leadstring) == NULL)
		{
		    /* Affix has a non-word character and isn't prepended to
		     * leader or appended to addition.  Need to use another
		     * word with an addition.  It's a copy of the basicword_T
		     * "bw". */
		    if (gap == &bw->bw_suffix)
		    {
			alen = ae->ae_add_nw - ae->ae_add;
			nbw = (basicword_T *)alloc((unsigned)(
				    sizeof(basicword_T) + STRLEN(bw->bw_word)
								 + alen + 1));
			if (nbw != NULL)
			{
			    *nbw = *bw;
			    ga_init2(&nbw->bw_prefix, sizeof(short_u), 1);
			    ga_init2(&nbw->bw_suffix, sizeof(short_u), 1);

			    /* Adding the suffix may change the caps. */
			    STRCPY(nword, dw->dw_word);
			    if (ae->ae_chop != NULL)
			    {
				/* Remove chop string. */
				p = nword + STRLEN(nword);
				for (i = mb_charlen(ae->ae_chop); i > 0; --i)
				    mb_ptr_back(nword, p);
				*p = NUL;
			    }
			    STRCAT(nword, ae->ae_add);
			    flags = captype(nword, nword + STRLEN(nword));
			    if (flags & BWF_KEEPCAP)
			    {
				nword[STRLEN(dw->dw_word) + alen] = NUL;
				nbw->bw_caseword = vim_strsave(nword);
			    }
			    nbw->bw_flags &= ~(BWF_ONECAP | BWF_ALLCAP
							       | BWF_KEEPCAP);
			    nbw->bw_flags |= flags;

			    if (bw->bw_leadstring != NULL)
				nbw->bw_leadstring =
					       vim_strsave(bw->bw_leadstring);
			    nbw->bw_addstring = vim_strsave(ae->ae_add_nw);

			    STRCPY(nbw->bw_word, bw->bw_word);
			    if (alen > 0 || ae->ae_chop != NULL)
			    {
				/* Suffix starts with word character.  Append
				 * it to the word.  Add new word entry. */
				wlen = STRLEN(nbw->bw_word);
				if (ae->ae_chop != NULL)
				    wlen -= STRLEN(ae->ae_chop);
				mch_memmove(nbw->bw_word + wlen, ae->ae_add,
									alen);
				nbw->bw_word[wlen + alen] = NUL;
				add_to_wordlist(newwords, nbw);
			    }
			    else
				/* Basic word is the same, link "nbw" after
				 * "bw". */
				bw->bw_next = nbw;

			    /* Remember this word, we need to set bw_prefix
			     * and bw_suffix later. */
			    if (ga_grow(&fixga, 1) == OK)
				((basicword_T **)fixga.ga_data)[fixga.ga_len++]
									= nbw;
			}
		    }
		    else
		    {
			/* TODO: prefix with non-word char */
		    }
		}
		else
		{
		    /* Affix applies to this word, add the related affix
		     * number.  But only if it's not there yet.  And keep the
		     * list sorted, so that we can compare it later. */
		    for (i = 0; i < gap->ga_len; ++i)
		    {
			n = ((short_u *)gap->ga_data)[i];
			if (n >= ae->ae_affnr)
			{
			    if (n == ae->ae_affnr)
				i = -1;
			    break;
			}
		    }
		    if (i >= 0 && ga_grow(gap, 1) == OK)
		    {
			if (i < gap->ga_len)
			    mch_memmove(((short_u *)gap->ga_data) + i + 1,
					((short_u *)gap->ga_data) + i,
					 sizeof(short_u) * (gap->ga_len - i));
			((short_u *)gap->ga_data)[i] = ae->ae_affnr;
			++gap->ga_len;
		    }
		}
	    }
	}
    }

    /*
     * For the words that we added for suffixes with non-word characters: Use
     * the prefix list of the main word.
     * TODO: do the same for prefixes.
     */
    for (i = 0; i < fixga.ga_len; ++i)
    {
	nbw = ((basicword_T **)fixga.ga_data)[i];
	if (ga_grow(&nbw->bw_prefix, bw->bw_prefix.ga_len) == OK)
	{
	    mch_memmove(nbw->bw_prefix.ga_data, bw->bw_prefix.ga_data,
				      bw->bw_prefix.ga_len * sizeof(short_u));
	    nbw->bw_prefix.ga_len = bw->bw_prefix.ga_len;
	}
    }

    ga_clear(&fixga);
}

/*
 * Go over all words in "oldwords" and change the old affix names to the new
 * affix numbers, check the conditions, fold case, extract the basic word and
 * additions.
 */
    static int
build_wordlist(newwords, oldwords, oldaff, regionmask)
    hashtab_T	*newwords;	/* basicword_T entries */
    hashtab_T	*oldwords;	/* dicword_T entries */
    afffile_T	*oldaff;	/* affixes for "oldwords" */
    int		regionmask;	/* value for bw_region */
{
    int		todo;
    hashitem_T	*old_hi;
    dicword_T	*dw;
    basicword_T *bw;
    char_u	foldword[MAXLINELEN];
    int		leadlen;
    char_u	leadstring[MAXLINELEN];
    int		addlen;
    char_u	addstring[MAXLINELEN];
    int		dwlen;
    char_u	*p;
    int		clen;
    int		flags;
    char_u	*cp;
    int		l;

    todo = oldwords->ht_used;
    for (old_hi = oldwords->ht_array; todo > 0; ++old_hi)
    {
	if (!HASHITEM_EMPTY(old_hi))
	{
	    --todo;
	    dw = HI2DW(old_hi);

	    /* This takes time, print a message now and then. */
	    if ((todo & 0x3ff) == 0 || todo == oldwords->ht_used - 1)
	    {
		if (todo != oldwords->ht_used - 1)
		{
		    msg_didout = FALSE;
		    msg_col = 0;
		}
		smsg((char_u *)_("%6d todo - %s"), todo, dw->dw_word);
		out_flush();
		ui_breakcheck();
		if (got_int)
		    break;
	    }

	    /* The basic words are always stored with folded case. */
	    dwlen = STRLEN(dw->dw_word);
	    (void)str_foldcase(dw->dw_word, dwlen, foldword, MAXLINELEN);
	    flags = captype(dw->dw_word, dw->dw_word + dwlen);

	    /* Check for non-word characters before the word. */
	    clen = 0;
	    leadlen = 0;
	    if (!spell_iswordc(foldword))
	    {
		p = foldword;
		for (;;)
		{
		    mb_ptr_adv(p);
		    ++clen;
		    if (*p == NUL)	/* Only non-word chars (bad word!) */
		    {
			if (p_verbose > 0)
			    smsg((char_u *)_("Warning: word without word characters: \"%s\""),
								    foldword);
			break;
		    }
		    if (spell_iswordc(p))
		    {
			/* Move the leader to "leadstring" and remove it from
			 * "foldword". */
			leadlen = p - foldword;
			mch_memmove(leadstring, foldword, leadlen);
			leadstring[leadlen] = NUL;
			mch_memmove(foldword, p, STRLEN(p) + 1);
			break;
		    }
		}
	    }

	    /* Check for non-word characters after word characters. */
	    addlen = 0;
	    for (p = foldword; spell_iswordc(p); mb_ptr_adv(p))
	    {
		if (*p == NUL)
		    break;
		++clen;
	    }
	    if (*p != NUL)
	    {
		/* Move the addition to "addstring" and truncate "foldword". */
		if (flags & BWF_KEEPCAP)
		{
		    /* Preserve caps, need to skip the right number of
		     * characters in the original word (case folding may
		     * change the byte count). */
		    l = 0;
		    for (cp = dw->dw_word; l < clen; mb_ptr_adv(cp))
			++l;
		    addlen = STRLEN(cp);
		    mch_memmove(addstring, cp, addlen + 1);
		}
		else
		{
		    addlen = STRLEN(p);
		    mch_memmove(addstring, p, addlen + 1);
		}
		*p = NUL;
	    }

	    bw = (basicword_T *)alloc_clear((unsigned)sizeof(basicword_T)
							  + STRLEN(foldword));
	    if (bw == NULL)
		break;
	    STRCPY(bw->bw_word, foldword);
	    bw->bw_region = regionmask;

	    if (leadlen > 0)
		bw->bw_leadstring = vim_strsave(leadstring);
	    else
		bw->bw_leadstring = NULL;
	    if (addlen > 0)
		bw->bw_addstring = vim_strsave(addstring);
	    else
		bw->bw_addstring = NULL;

	    add_to_wordlist(newwords, bw);

	    if (flags & BWF_KEEPCAP)
	    {
		if (addlen == 0)
		    /* use the whole word */
		    bw->bw_caseword = vim_strsave(dw->dw_word + leadlen);
		else
		    /* use only up to the addition */
		    bw->bw_caseword = vim_strnsave(dw->dw_word + leadlen,
						  cp - dw->dw_word - leadlen);
		if (bw->bw_caseword == NULL)	/* out of memory */
		    flags &= ~BWF_KEEPCAP;
	    }
	    bw->bw_flags = flags;

	    /* Deal with any affix names on the old word, translate them
	     * into affix numbers. */
	    ga_init2(&bw->bw_prefix, sizeof(short_u), 10);
	    ga_init2(&bw->bw_suffix, sizeof(short_u), 10);
	    if (dw->dw_affnm != NULL)
		trans_affixes(dw, bw, oldaff, newwords);
	}
    }
    if (todo > 0)
	return FAIL;
    return OK;
}

/*
 * Go through the list of words and combine the ones that are identical except
 * for the region.
 */
    static void
combine_regions(newwords)
    hashtab_T	*newwords;
{
    int		todo;
    hashitem_T	*hi;
    basicword_T *bw, *nbw, *pbw;

    /* Loop over all basic words in the words table. */
    todo = newwords->ht_used;
    for (hi = newwords->ht_array; todo > 0; ++hi)
    {
	if (!HASHITEM_EMPTY(hi))
	{
	    --todo;

	    /* Loop over the list of words for this basic word.  Compare with
	     * each following word in the same list. */
	    for (bw = HI2BW(hi); bw != NULL; bw = bw->bw_next)
	    {
		pbw = bw;
		for (nbw = pbw->bw_next; nbw != NULL; nbw = pbw->bw_next)
		{
		    if (bw->bw_flags == nbw->bw_flags
			    && (bw->bw_leadstring == NULL)
					       == (nbw->bw_leadstring == NULL)
			    && (bw->bw_addstring == NULL)
						== (nbw->bw_addstring == NULL)
			    && ((bw->bw_flags & BWF_KEEPCAP) == 0
				|| (STRCMP(bw->bw_caseword,
						      nbw->bw_caseword) == 0))
			    && (bw->bw_leadstring == NULL
				|| (STRCMP(bw->bw_leadstring,
						    nbw->bw_leadstring) == 0))
			    && (bw->bw_addstring == NULL
				|| (STRCMP(bw->bw_addstring,
						     nbw->bw_addstring) == 0))
			    && same_affixes(bw, nbw)
			    )
		    {
			/* Match, combine regions and delete "nbw". */
			pbw->bw_next = nbw->bw_next;
			bw->bw_region |= nbw->bw_region;
			free_basicword(nbw);
		    }
		    else
			/* No match, continue with next one. */
			pbw = nbw;
		}
	    }
	}
    }
}

/*
 * Return TRUE when the prefixes and suffixes for "bw" and "nbw" are equal.
 */
    static int
same_affixes(bw, nbw)
    basicword_T	*bw;
    basicword_T	*nbw;
{
    return (bw->bw_prefix.ga_len == nbw->bw_prefix.ga_len
	    && bw->bw_suffix.ga_len == nbw->bw_suffix.ga_len
	    && (bw->bw_prefix.ga_len == 0
		|| vim_memcmp(bw->bw_prefix.ga_data,
		    nbw->bw_prefix.ga_data,
		    bw->bw_prefix.ga_len * sizeof(short_u)) == 0)
	    && (bw->bw_suffix.ga_len == 0
		|| vim_memcmp(bw->bw_suffix.ga_data,
		    nbw->bw_suffix.ga_data,
		    bw->bw_suffix.ga_len * sizeof(short_u)) == 0));
}

/*
 * For each basic word with additions turn the affixes into other additions
 * and/or new basic words.  The result is that no affixes apply to a word with
 * additions.
 */
    static void
expand_affixes(newwords, prefgap, suffgap)
    hashtab_T	*newwords;
    garray_T	*prefgap;
    garray_T	*suffgap;
{
    int		todo;
    hashitem_T	*hi;
    basicword_T *bw;
    int		pi, si;
    affentry_T	*pae, *sae;
    garray_T	add_words;
    int		n;

    ga_init2(&add_words, sizeof(basicword_T *), 10);

    todo = newwords->ht_used;
    for (hi = newwords->ht_array; todo > 0; ++hi)
    {
	if (!HASHITEM_EMPTY(hi))
	{
	    --todo;
	    for (bw = HI2BW(hi); bw != NULL; bw = bw->bw_next)
	    {
		/*
		 * Need to fix affixes if there is a leader or addition and
		 * there are prefixes or suffixes.
		 */
		if ((bw->bw_leadstring != NULL || bw->bw_addstring != NULL)
			&& (bw->bw_prefix.ga_len != 0
						|| bw->bw_suffix.ga_len != 0))
		{
		    /* Loop over all prefix numbers, but first without a
		     * prefix. */
		    for (pi = -1; pi < bw->bw_prefix.ga_len; ++pi)
		    {
			pae = NULL;
			if (pi >= 0)
			{
			    n = ((short_u *)bw->bw_prefix.ga_data)[pi];
			    pae = ((affheader_T *)prefgap->ga_data + n)
								   ->ah_first;
			}

			/* Loop over all entries for prefix "pi".  Do it once
			 * when there is no prefix (pi == -1). */
			do
			{
			    /* Loop over all suffix numbers.  Do without a
			     * suffix first when there is a prefix. */
			    for (si = (pi == -1 ? 0 : -1);
					      si < bw->bw_suffix.ga_len; ++si)
			    {
				sae = NULL;
				if (si >= 0)
				{
				    n = ((short_u *)bw->bw_suffix.ga_data)[si];
				    sae = ((affheader_T *)suffgap->ga_data + n)
								   ->ah_first;
				}

				/* Loop over all entries for suffix "si".  Do
				 * it once when there is no suffix (si == -1).
				 */
				do
				{
				    /* Expand the word for this combination of
				     * prefixes and affixes. */
				    expand_one_aff(bw, &add_words, pae, sae);

				    /* Advance to next suffix entry, if there
				     * is one. */
				    if (sae != NULL)
					sae = sae->ae_next;
				} while (sae != NULL);
			    }

			    /* Advance to next prefix entry, if there is one. */
			    if (pae != NULL)
				pae = pae->ae_next;
			} while (pae != NULL);
		    }
		}
	    }
	}
    }

    /*
     * Add the new words afterwards, can't change "newwords" while going over
     * all its items.
     */
    for (pi = 0; pi < add_words.ga_len; ++pi)
	add_to_wordlist(newwords, ((basicword_T **)add_words.ga_data)[pi]);

    ga_clear(&add_words);
}

/*
 * Add one word to "add_words" for basic word "bw" with additions, adding
 * prefix "pae" and suffix "sae".  Either "pae" or "sae" can be NULL.
 */
    static void
expand_one_aff(bw, add_words, pae, sae)
    basicword_T	    *bw;
    garray_T	    *add_words;
    affentry_T	    *pae;
    affentry_T	    *sae;
{
    char_u	word[MAXWLEN + 1];
    char_u	caseword[MAXWLEN + 1];
    int		l = 0;
    int		choplen = 0;
    int		ll;
    basicword_T	*nbw;

    /* Prepend prefix to the basic word if there is a prefix and there is no
     * leadstring. */
    if (pae != NULL && bw->bw_leadstring == NULL)
    {
	if (pae->ae_add != NULL)
	{
	    l = STRLEN(pae->ae_add);
	    mch_memmove(word, pae->ae_add, l);
	}
	if (pae->ae_chop != NULL)
	    choplen = STRLEN(pae->ae_chop);
    }

    /* Copy the body of the word. */
    STRCPY(word + l, bw->bw_word + choplen);

    /* Do the same for bw_caseword, if it's there. */
    if (bw->bw_flags & BWF_KEEPCAP)
    {
	if (l > 0)
	    mch_memmove(caseword, pae->ae_add, l);
	STRCPY(caseword + l, bw->bw_caseword + choplen);
    }

    /* Append suffix to the basic word if there is a suffix and there is no
     * addstring. */
    if (sae != 0 && bw->bw_addstring == NULL)
    {
	l = STRLEN(word);
	if (sae->ae_chop != NULL)
	    l -= STRLEN(sae->ae_chop);
	if (sae->ae_add == NULL)
	    word[l] = NUL;
	else
	    STRCPY(word + l, sae->ae_add);

	if (bw->bw_flags & BWF_KEEPCAP)
	{
	    /* Do the same for the caseword. */
	    l = STRLEN(caseword);
	    if (sae->ae_chop != NULL)
		l -= STRLEN(sae->ae_chop);
	    if (sae->ae_add == NULL)
		caseword[l] = NUL;
	    else
		STRCPY(caseword + l, sae->ae_add);
	}
    }

    nbw = (basicword_T *)alloc_clear((unsigned)
					  sizeof(basicword_T) + STRLEN(word));
    if (nbw != NULL)
    {
	/* Add the new word to the list of words to be added later. */
	if (ga_grow(add_words, 1) == FAIL)
	{
	    vim_free(nbw);
	    return;
	}
	((basicword_T **)add_words->ga_data)[add_words->ga_len++] = nbw;

	/* Copy the (modified) basic word, flags and region. */
	STRCPY(nbw->bw_word, word);
	nbw->bw_flags = bw->bw_flags;
	nbw->bw_region = bw->bw_region;

	/* Set the (modified) caseword. */
	if (bw->bw_flags & BWF_KEEPCAP)
	    if ((nbw->bw_caseword = vim_strsave(caseword)) == NULL)
		nbw->bw_flags &= ~BWF_KEEPCAP;

	if (bw->bw_leadstring != NULL)
	{
	    if (pae != NULL)
	    {
		/* Prepend prefix to leadstring. */
		ll = STRLEN(bw->bw_leadstring);
		l = choplen = 0;
		if (pae->ae_add != NULL)
		    l = STRLEN(pae->ae_add);
		if (pae->ae_chop != NULL)
		{
		    choplen = STRLEN(pae->ae_chop);
		    if (choplen > ll)	    /* TODO: error? */
			choplen = ll;
		}
		nbw->bw_leadstring = alloc((unsigned)(ll + l - choplen + 1));
		if (nbw->bw_leadstring != NULL)
		{
		    if (l > 0)
			mch_memmove(nbw->bw_leadstring, pae->ae_add, l);
		    STRCPY(nbw->bw_leadstring + l, bw->bw_leadstring + choplen);
		}
	    }
	    else
		nbw->bw_leadstring = vim_strsave(bw->bw_leadstring);
	}

	if (bw->bw_addstring != NULL)
	{
	    if (sae != NULL)
	    {
		/* Append suffix to addstring. */
		l = STRLEN(bw->bw_addstring);
		if (sae->ae_chop != NULL)
		{
		    l -= STRLEN(sae->ae_chop);
		    if (l < 0)	    /* TODO: error? */
			l = 0;
		}
		if (sae->ae_add == NULL)
		    ll = 0;
		else
		    ll = STRLEN(sae->ae_add);
		nbw->bw_addstring = alloc((unsigned)(ll + l - choplen + 1));
		if (nbw->bw_addstring != NULL)
		{
		    STRCPY(nbw->bw_addstring, bw->bw_addstring);
		    if (sae->ae_add == NULL)
			nbw->bw_addstring[l] = NUL;
		    else
			STRCPY(nbw->bw_addstring + l, sae->ae_add);
		}
	    }
	    else
		nbw->bw_addstring = vim_strsave(bw->bw_addstring);
	}
    }
}

/*
 * Add basicword_T "*bw" to wordlist "newwords".
 */
    static void
add_to_wordlist(newwords, bw)
    hashtab_T	*newwords;
    basicword_T	*bw;
{
    hashitem_T	*hi;
    basicword_T *bw2;

    hi = hash_find(newwords, bw->bw_word);
    if (HASHITEM_EMPTY(hi))
    {
	/* New entry, add to hashlist. */
	hash_add(newwords, bw->bw_word);
	bw->bw_next = NULL;
    }
    else
    {
	/* Existing entry, append to list of basic words. */
	bw2 = HI2BW(hi);
	bw->bw_next = bw2->bw_next;
	bw2->bw_next = bw;
    }
}

/*
 * Write a number to file "fd", MSB first, in "len" bytes.
 */
    static void
put_bytes(fd, nr, len)
    FILE    *fd;
    long_u  nr;
    int	    len;
{
    int	    i;

    for (i = len - 1; i >= 0; --i)
	putc((int)(nr >> (i * 8)), fd);
}

/*
 * Write affix info.  <affflags> <affitemcnt> <affitem> ...
 */
    static void
write_affix(fd, ah)
    FILE	*fd;
    affheader_T	*ah;
{
    int		i = 0;
    affentry_T	*ae;
    char_u	*p;
    int		round;

    fputc(ah->ah_combine ? 1 : 0, fd);		/* <affflags> */

    /* Count the number of entries. */
    for (ae = ah->ah_first; ae != NULL; ae = ae->ae_next)
	++i;
    put_bytes(fd, (long_u)i, 2);		/* <affitemcnt> */

    for (ae = ah->ah_first; ae != NULL; ae = ae->ae_next)
	for (round = 1; round <= 2; ++round)
	{
	    p = round == 1 ? ae->ae_chop : ae->ae_add;
	    if (p == NULL)
		putc(0, fd);		/* <affchoplen> / <affaddlen> */
	    else
	    {
		putc(STRLEN(p), fd);	/* <affchoplen> / <affaddlen> */
					/* <affchop> / <affadd> */
		fwrite(p, STRLEN(p), (size_t)1, fd);
	    }
	}
}

/*
 * Write list of affix NRs: <affixcnt> <affixNR> ...
 */
    static void
write_affixlist(fd, aff, bytes)
    FILE	*fd;
    garray_T	*aff;
    int		bytes;
{
    int		i;

    if (aff->ga_len > 0)
    {
	putc(aff->ga_len, fd);	    /* <affixcnt> */
	for (i = 0; i < aff->ga_len; ++i)
	    put_bytes(fd, (long_u )((short_u *)aff->ga_data)[i], bytes);
    }
}

/*
 * Vim spell file format:  <HEADER> <PREFIXLIST> <SUFFIXLIST>
 *						    <SUGGEST> <WORDLIST>
 *
 * <HEADER>: <fileID> <regioncnt> <regionname> ...
 *
 * <fileID>     10 bytes    "VIMspell01"
 * <regioncnt>  1 byte	    number of regions following (8 supported)
 * <regionname>	2 bytes     Region name: ca, au, etc.
 *			    First <regionname> is region 1.
 *
 *
 * <PREFIXLIST>: <affcount> <afftotcnt> <affix> ...
 * <SUFFIXLIST>: <affcount> <afftotcnt> <affix> ...
 *		list of possible affixes: prefixes and suffixes.
 *
 * <affcount>	2 bytes	    Number of affixes (MSB comes first).
 *                          When more than 256 an affixNR is 2 bytes.
 *                          This is separate for prefixes and suffixes!
 *                          First affixNR is 0.
 * <afftotcnt>	2 bytes	    Total number of affix items (MSB comes first).
 *
 * <affix>: <affflags> <affitemcnt> <affitem> ...
 *
 * <affflags>	1 byte	    0x01: prefix combines with suffix.
 *			    0x02-0x80: unset
 * <affitemcnt> 2 bytes	    Number of affixes with this affixNR (MSB first).
 *
 * <affitem>: <affchoplen> <affchop> <affaddlen> <affadd>
 *
 * <affchoplen> 1 byte	    Length of <affchop> in bytes.
 * <affchop>    N bytes     To be removed from basic word.
 * <affaddlen>  1 byte	    Length of <affadd> in bytes.
 * <affadd>     N bytes     To be added to basic word.
 *
 *
 * <SUGGEST> : <suggestlen> <more> ...
 *
 * <suggestlen> 4 bytes	    Length of <SUGGEST> in bytes, excluding
 *			    <suggestlen>.  MSB first.
 * <more>		    To be defined.
 *
 *
 * <WORDLIST>: <wordcount> <worditem> ...
 *
 * <wordcount>	4 bytes	    Number of <worditem> following.  MSB first.
 *
 * <worditem>: <nr> <string> <flags> [<flags2>]
 *			  [<caselen> <caseword>]
 *			  [<affixcnt> <affixNR> ...]    (prefixes)
 *			  [<affixcnt> <affixNR> ...]	(suffixes)
 *			  [<region>]
 *			  [<addcnt> <add> ...]
 *
 * <nr>	i	1 byte	    Number of bytes copied from previous word.
 * <string>	N bytes	    Additional bytes for word, up to byte smaller than
 *			    0x20 (space).
 *			    Must only contain case-folded word characters.
 * <flags>	1 byte	    0x01: word is valid without addition
 *			    0x02: has region byte
 *			    0x04: first letter must be upper-case
 *			    0x08: has suffixes, <affixcnt> and <affixNR> follow
 *			    0x10: more flags, <flags2> follows next
 *			    0x20-0x80: can't be used, unset
 * <flags2>	1 byte	    0x01: has additions, <addcnt> and <add> follow
 *			    0x02: has prefixes, <affixcnt> and <affixNR> follow
 *			    0x04: all letters must be upper-case
 *			    0x08: case must match
 *			    0x10-0x80: unset
 * <caselen>	1 byte	    Length of <caseword>.
 * <caseword>	N bytes	    Word with matching case.
 * <affixcnt>	1 byte	    Number of affix NRs following.
 * <affixNR>	1 or 2 byte Number of possible affix for this word.
 *			    When using 2 bytes MSB comes first.
 * <region>	1 byte	    Bitmask for regions in which word is valid.  When
 *			    omitted it's valid in all regions.
 *			    Lowest bit is for region 1.
 * <addcnt>	2 bytes	    Number of <add> items following.
 *
 * <add>: <addflags> <addlen> [<leadlen> <addstring>] [<region>]
 *
 * <addflags>	1 byte	    0x01: fixed case, <addstring> is the whole word
 *				  with matching case.
 *			    0x02: first letter must be upper-case
 *			    0x04: all letters must be upper-case
 *			    0x08: has region byte
 *			    0x10-0x80: unset
 * <addlen>	1 byte	    Length of <addstring> in bytes.
 * <leadlen>	1 byte	    Number of bytes at start of <addstring> that must
 *			    come before the start of the basic word.
 * <addstring>	N bytes	    Word characters, before/in/after the word.
 *
 * All text characters are in 'encoding': <affchop>, <affadd>, <string>,
 * <caseword>> and <addstring>.
 * All other fields are ASCII: <regionname>
 * <string> is always case-folded.
 */

/*
 * Write the Vim spell file "fname".
 */
    static void
write_vim_spell(fname, prefga, suffga, newwords, regcount, regchars)
    char_u	*fname;
    garray_T	*prefga;	/* prefixes, affheader_T entries */
    garray_T	*suffga;	/* suffixes, affheader_T entries */
    hashtab_T	*newwords;	/* basic words, basicword_T entries */
    int		regcount;	/* number of regions */
    char_u	*regchars;	/* region names */
{
    FILE	*fd;
    garray_T	*gap;
    hashitem_T	*hi;
    char_u	**wtab;
    int		todo;
    int		flags, aflags;
    basicword_T	*bw, *bwf, *bw2, *prevbw = NULL;
    int		regionmask;	/* mask for all relevant region bits */
    int		i;
    int		cnt;
    affentry_T	*ae;
    int		round;
    int		prefm, suffm;
    garray_T	bwga;

    fd = fopen((char *)fname, "w");
    if (fd == NULL)
    {
	EMSG2(_(e_notopen), fname);
	return;
    }

    fwrite(VIMSPELLMAGIC, VIMSPELLMAGICL, (size_t)1, fd);

    /* write the region names if there is more than one */
    if (regcount > 1)
    {
	putc(regcount, fd);
	fwrite(regchars, (size_t)(regcount * 2), (size_t)1, fd);
	regionmask = (1 << regcount) - 1;
    }
    else
    {
	putc(0, fd);
	regionmask = 0;
    }

    /* Write the prefix and suffix lists. */
    for (round = 1; round <= 2; ++round)
    {
	gap = round == 1 ? prefga : suffga;
	put_bytes(fd, (long_u)gap->ga_len, 2);	    /* <affcount> */

	/* Count the total number of affix items. */
	cnt = 0;
	for (i = 0; i < gap->ga_len; ++i)
	    for (ae = ((affheader_T *)gap->ga_data + i)->ah_first;
						 ae != NULL; ae = ae->ae_next)
		++cnt;
	put_bytes(fd, (long_u)cnt, 2);		    /* <afftotcnt> */

	for (i = 0; i < gap->ga_len; ++i)
	    write_affix(fd, (affheader_T *)gap->ga_data + i);
    }

    /* Number of bytes used for affix NR depends on affix count. */
    prefm = (prefga->ga_len > 256) ? 2 : 1;
    suffm = (suffga->ga_len > 256) ? 2 : 1;

    /* Write the suggest info. TODO */
    put_bytes(fd, 0L, 4);

    /*
     * Write the word list.  <wordcount> <worditem> ...
     */
    /* number of basic words in 4 bytes */
    put_bytes(fd, newwords->ht_used, 4);	    /* <wordcount> */

    /*
     * Sort the word list, so that we can reuse as many bytes as possible.
     */
    wtab = (char_u **)alloc((unsigned)(sizeof(char_u *) * newwords->ht_used));
    if (wtab != NULL)
    {
	/* Make a table with pointers to each word. */
	todo = newwords->ht_used;
	for (hi = newwords->ht_array; todo > 0; ++hi)
	    if (!HASHITEM_EMPTY(hi))
		wtab[--todo] = hi->hi_key;

	/* Sort. */
	sort_strings(wtab, (int)newwords->ht_used);

	/* Now write each basic word to the spell file. */
	ga_init2(&bwga, sizeof(basicword_T *), 10);
	for (todo = 0; todo < newwords->ht_used; ++todo)
	{
	    bwf = KEY2BW(wtab[todo]);

	    /*
	     * Reorder the list of basicword_T words: make a list for words
	     * with the same case-folded word.  Put them together for same
	     * caps (ONECAP, ALLCAP and various KEEPCAP words) and same
	     * affixes.  Each list will then be put as a basic word with
	     * additions.
	     * This won't take much space, since the basic word is the same
	     * every time, only its length is written.
	     */
	    bwga.ga_len = 0;
	    for (bw = bwf; bw != NULL; bw = bw->bw_next)
	    {
		flags = bw->bw_flags & (BWF_ONECAP | BWF_KEEPCAP | BWF_ALLCAP);

		/* Go through the lists we found so far.  Break when the case
		 * matches. */
		for (i = 0; i < bwga.ga_len; ++i)
		{
		    bw2 = ((basicword_T **)bwga.ga_data)[i];
		    aflags = bw2->bw_flags & (BWF_ONECAP | BWF_KEEPCAP
								| BWF_ALLCAP);
		    if (flags == aflags
			    && ((flags & BWF_KEEPCAP) == 0
				|| (STRCMP(bw->bw_caseword,
						     bw2->bw_caseword) == 0))
			    && same_affixes(bw, bw2))
			break;
		}
		if (i == bwga.ga_len)
		{
		    /* No word with similar caps, make a new list. */
		    if (ga_grow(&bwga, 1) == FAIL)
			break;
		    ((basicword_T **)bwga.ga_data)[i] = bw;
		    bw->bw_cnext = NULL;
		    ++bwga.ga_len;
		}
		else
		{
		    /* Add to list of words with similar caps. */
		    bw->bw_cnext = bw2->bw_cnext;
		    bw2->bw_cnext = bw;
		}
	    }

	    /* Prefer the word with no caps to use as the first basic word.
	     * At least one without KEEPCAP. */
	    bw = NULL;
	    for (i = 0; i < bwga.ga_len; ++i)
	    {
		bw2 = ((basicword_T **)bwga.ga_data)[i];
		if (bw == NULL
			|| (bw2->bw_flags & (BWF_ONECAP | BWF_KEEPCAP
							  | BWF_ALLCAP)) == 0
			|| (bw->bw_flags & BWF_KEEPCAP))
		    bw = bw2;
	    }

	    /* Write first basic word.  If it's KEEPCAP then we need a word
	     * without VALID flag first (makes it easier to read the list back
	     * in). */
	    if (bw->bw_flags & BWF_KEEPCAP)
		write_bword(fd, bw, TRUE, &prevbw, regionmask, prefm, suffm);
	    write_bword(fd, bw, FALSE, &prevbw, regionmask, prefm, suffm);

	    /* Write other basic words, with different caps. */
	    for (i = 0; i < bwga.ga_len; ++i)
	    {
		bw2 = ((basicword_T **)bwga.ga_data)[i];
		if (bw2 != bw)
		    write_bword(fd, bw2, FALSE, &prevbw, regionmask,
								prefm, suffm);
	    }
	}

	ga_clear(&bwga);
    }

    fclose(fd);
}

/*
 * Write basic word, followed by any additions.
 *
 * <worditem>: <nr> <string> <flags> [<flags2>]
 *			  [<caselen> <caseword>]
 *			  [<affixcnt> <affixNR> ...]    (prefixes)
 *			  [<affixcnt> <affixNR> ...]	(suffixes)
 *			  [<region>]
 *			  [<addcnt> <add> ...]
 */
    static void
write_bword(fd, bwf, lowcap, prevbw, regionmask, prefm, suffm)
    FILE	*fd;
    basicword_T	*bwf;
    int		lowcap;		/* write KEEPKAP word as not-valid */
    basicword_T **prevbw;	/* last written basic word */
    int		regionmask;	/* mask that includes all possible regions */
    int		prefm;
    int		suffm;
{
    int		flags;
    int		aflags;
    int		len;
    int		leadlen, addlen;
    int		clen;
    int		adds = 0;
    int		i;
    basicword_T *bw, *bw2;

    /* Check how many bytes can be copied from the previous word. */
    len = STRLEN(bwf->bw_word);
    if (*prevbw == NULL)
	clen = 0;
    else
	for (clen = 0; clen < len
		&& (*prevbw)->bw_word[clen] == bwf->bw_word[clen]; ++clen)
	    ;
    putc(clen, fd);				/* <nr> */
    *prevbw = bwf;
						/* <string> */
    if (len > clen)
	fwrite(bwf->bw_word + clen, (size_t)(len - clen), (size_t)1, fd);

    /* Try to find a word without additions to use first. */
    bw = bwf;
    for (bw2 = bwf; bw2 != NULL; bw2 = bw2->bw_cnext)
    {
	if (bw2->bw_addstring != NULL || bw2->bw_leadstring != NULL)
	    ++adds;
	else
	    bw = bw2;
    }

    /* Flags: If there is no leadstring and no addstring the basic word is
     * valid, may have prefixes, suffixes and region. */
    flags = bw->bw_flags;
    if (bw->bw_addstring == NULL && bw->bw_leadstring == NULL)
    {
	flags |= BWF_VALID;

	/* Add the prefix/suffix list if there are prefixes/suffixes. */
	if (bw->bw_prefix.ga_len > 0)
	    flags |= BWF_PREFIX;
	if (bw->bw_suffix.ga_len > 0)
	    flags |= BWF_SUFFIX;

	/* Flags: add the region byte if the word isn't valid in all
	 * regions. */
	if (regionmask != 0 && (bw->bw_region & regionmask) != regionmask)
	    flags |= BWF_REGION;
    }

    /* Flags: may have additions. */
    if (adds > 0)
	flags |= BWF_ADDS;

    /* The dummy word before a KEEPCAP word doesn't have any flags, they are
     * in the actual word that follows. */
    if (lowcap)
	flags = 0;

    /* Flags: when the upper byte is not used we only write one flags
     * byte, if it's used then set an extra flag in the first byte and
     * also write the second byte. */
    if ((flags & 0xff00) == 0)
	putc(flags, fd);			/* <flags> */
    else
    {
	putc(flags | BWF_SECOND, fd);		/* <flags> */
	putc((int)((unsigned)flags >> 8), fd);	/* <flags2> */
    }

    /* First dummy word doesn't need anything but flags. */
    if (lowcap)
	return;

    if (flags & BWF_KEEPCAP)
    {
	len = STRLEN(bw->bw_caseword);
	putc(len, fd);			/* <caselen> */
	for (i = 0; i < len; ++i)
	    putc(bw->bw_caseword[i], fd);	/* <caseword> */
    }

    /* write prefix and suffix lists: <affixcnt> <affixNR> ... */
    if (flags & BWF_PREFIX)
	write_affixlist(fd, &bw->bw_prefix, prefm);
    if (flags & BWF_SUFFIX)
	write_affixlist(fd, &bw->bw_suffix, suffm);

    if (flags & BWF_REGION)
	putc(bw->bw_region, fd);		/* <region> */

    /*
     * Additions.
     */
    if (adds > 0)
    {
	put_bytes(fd, (long_u)adds, 2);		/* <addcnt> */

	for (bw = bwf; bw != NULL; bw = bw->bw_cnext)
	    if (bw->bw_leadstring != NULL || bw->bw_addstring != NULL)
	    {
		/* <add>: <addflags> <addlen> [<leadlen> <addstring>]
		 *	  [<region>] */
		aflags = 0;
		if (bw->bw_flags & BWF_ONECAP)
		    aflags |= ADD_ONECAP;
		if (bw->bw_flags & BWF_ALLCAP)
		    aflags |= ADD_ALLCAP;
		if (bw->bw_flags & BWF_KEEPCAP)
		    aflags |= ADD_KEEPCAP;
		if (regionmask != 0
				&& (bw->bw_region & regionmask) != regionmask)
		    aflags |= ADD_REGION;
		putc(aflags, fd);		    /* <addflags> */

		if (bw->bw_leadstring == NULL)
		    leadlen = 0;
		else
		    leadlen = STRLEN(bw->bw_leadstring);
		if (bw->bw_addstring == NULL)
		    addlen = 0;
		else
		    addlen = STRLEN(bw->bw_addstring);
		putc(leadlen + addlen, fd);		    /* <addlen> */
		putc(leadlen, fd);			    /* <leadlen> */
							    /* <addstring> */
		if (bw->bw_leadstring != NULL)
		    fwrite(bw->bw_leadstring, (size_t)leadlen, (size_t)1, fd);
		if (bw->bw_addstring != NULL)
		    fwrite(bw->bw_addstring, (size_t)addlen, (size_t)1, fd);

		if (aflags & ADD_REGION)
		    putc(bw->bw_region, fd);		/* <region> */
	    }
    }
}


/*
 * ":mkspell  outfile  infile ..."
 */
    void
ex_mkspell(eap)
    exarg_T *eap;
{
    int		fcount;
    char_u	**fnames;
    char_u	fname[MAXPATHL];
    char_u	wfname[MAXPATHL];
    afffile_T	*(afile[8]);
    hashtab_T	dfile[8];
    int		i;
    int		len;
    char_u	region_name[16];
    struct stat	st;
    int		round;
    vimconv_T	conv;

    /* Expand all the arguments (e.g., $VIMRUNTIME). */
    if (get_arglist_exp(eap->arg, &fcount, &fnames) == FAIL)
	return;
    if (fcount < 2)
	EMSG(_(e_invarg));	/* need at least output and input names */
    else if (fcount > 9)
	EMSG(_("E754: Only up to 8 regions supported"));
    else
    {
	/* Check for overwriting before doing things that may take a lot of
	 * time. */
	sprintf((char *)wfname, "%s.%s.spl", fnames[0], p_enc);
	if (!eap->forceit && mch_stat((char *)wfname, &st) >= 0)
	{
	    EMSG(_(e_exists));
	    goto theend;
	}
	if (mch_isdir(fnames[0]))
	{
	    EMSG2(_(e_isadir2), fnames[0]);
	    goto theend;
	}

	/*
	 * Init the aff and dic pointers.
	 * Get the region names if there are more than 2 arguments.
	 */
	for (i = 1; i < fcount; ++i)
	{
	    afile[i - 1] = NULL;
	    hash_init(&dfile[i - 1]);
	    if (fcount > 2)
	    {
		len = STRLEN(fnames[i]);
		if (STRLEN(gettail(fnames[i])) < 5 || fnames[i][len - 3] != '_')
		{
		    EMSG2(_("E755: Invalid region in %s"), fnames[i]);
		    goto theend;
		}
		else
		{
		    region_name[(i - 1) * 2] = TOLOWER_ASC(fnames[i][len - 2]);
		    region_name[(i - 1) * 2 + 1] =
					      TOLOWER_ASC(fnames[i][len - 1]);
		}
	    }
	}

	/*
	 * Read all the .aff and .dic files.
	 * Text is converted to 'encoding'.
	 */
	for (i = 1; i < fcount; ++i)
	{
	    /* Read the .aff file.  Will init "conv" based on the "SET" line. */
	    conv.vc_type = CONV_NONE;
	    sprintf((char *)fname, "%s.aff", fnames[i]);
	    if ((afile[i - 1] = spell_read_aff(fname, &conv)) == NULL)
		break;

	    /* Read the .dic file. */
	    sprintf((char *)fname, "%s.dic", fnames[i]);
	    if (spell_read_dic(&dfile[i - 1], fname, &conv) == FAIL)
		break;

	    /* Free any conversion stuff. */
	    convert_setup(&conv, NULL, NULL);
	}

	/* Process the data when all the files could be read. */
	if (i == fcount)
	{
	    garray_T	prefga;
	    garray_T	suffga;
	    garray_T	*gap;
	    hashtab_T	newwords;

	    /*
	     * Combine all the affixes into one new affix list.  This is done
	     * for prefixes and suffixes separately.
	     * We need to do this for each region, try to re-use the same
	     * affixes.
	     * Since we number the new affix entries, a growarray will do.  In
	     * the affheader_T the ah_key is unused.
	     */
	    MSG(_("Combining affixes..."));
	    out_flush();
	    for (round = 1; round <= 2; ++round)
	    {
		gap = round == 1 ? &prefga : &suffga;
		ga_init2(gap, sizeof(affheader_T), 50);
		for (i = 1; i < fcount; ++i)
		    get_new_aff(round == 1 ? &afile[i - 1]->af_pref
					   : &afile[i - 1]->af_suff, gap);
	    }

	    /*
	     * Go over all words and:
	     * - change the old affix names to the new affix numbers
	     * - check the conditions
	     * - fold case
	     * - extract the basic word and additions.
	     * Do this for each region.
	     */
	    MSG(_("Building word list..."));
	    out_flush();
	    hash_init(&newwords);

	    for (i = 1; i < fcount; ++i)
		build_wordlist(&newwords, &dfile[i - 1], afile[i - 1],
								1 << (i - 1));

	    if (fcount > 2)
	    {
		/* Combine words for the different regions into one. */
		MSG(_("Combining regions..."));
		out_flush();
		combine_regions(&newwords);
	    }

	    /*
	     * Affixes on a word with additions are clumsy, would require
	     * inefficient searching.  Turn the affixes into additions and/or
	     * the expanded word.
	     */
	    MSG(_("Processing words..."));
	    out_flush();
	    expand_affixes(&newwords, &prefga, &suffga);

	    /* Write the info in the spell file. */
	    smsg((char_u *)_("Writing spell file %s..."), wfname);
	    out_flush();
	    write_vim_spell(wfname, &prefga, &suffga, &newwords,
						     fcount - 1, region_name);
	    MSG(_("Done!"));
	    out_flush();

	    /* Free the allocated stuff. */
	    free_wordtable(&newwords);
	    for (round = 1; round <= 2; ++round)
	    {
		gap = round == 1 ? &prefga: &suffga;
		for (i = 0; i < gap->ga_len; ++i)
		    free_affixentries(((affheader_T *)gap->ga_data + i)
								  ->ah_first);
		ga_clear(gap);
	    }
	}

	/* Free the .aff and .dic file structures. */
	for (i = 1; i < fcount; ++i)
	{
	    if (afile[i - 1] != NULL)
		spell_free_aff(afile[i - 1]);
	    spell_free_dic(&dfile[i - 1]);
	}
    }

theend:
    FreeWild(fcount, fnames);
}

    static void
free_wordtable(ht)
    hashtab_T	*ht;
{
    int		todo;
    basicword_T	*bw, *nbw;
    hashitem_T	*hi;

    todo = ht->ht_used;
    for (hi = ht->ht_array; todo > 0; ++hi)
    {
	if (!HASHITEM_EMPTY(hi))
	{
	    --todo;
	    for (bw = HI2BW(hi); bw != NULL; bw = nbw)
	    {
		nbw = bw->bw_next;
		free_basicword(bw);
	    }
	}
    }
}

/*
 * Free a basicword_T and what it contains.
 */
    static void
free_basicword(bw)
    basicword_T	*bw;
{
    ga_clear(&bw->bw_prefix);
    ga_clear(&bw->bw_suffix);
    vim_free(bw->bw_caseword);
    vim_free(bw->bw_leadstring);
    vim_free(bw->bw_addstring);
    vim_free(bw);
}

/*
 * Free a list of affentry_T.
 */
    static void
free_affixentries(first)
    affentry_T	*first;
{
    affentry_T	*ap, *an;

    for (ap = first; ap != NULL; ap = an)
    {
	an = ap->ae_next;
	vim_free(ap->ae_chop);
	vim_free(ap->ae_add);
	vim_free(ap->ae_cond);
	vim_free(ap->ae_prog);
	vim_free(ap);
    }
}

#endif  /* FEAT_MBYTE */

#endif  /* FEAT_SYN_HL */

#if 0  /* old spell code with words in .spl file */
/*
 * Structure that is used to store the text from the language file.  This
 * avoids the need to allocate space for each individual word.  It's allocated
 * in big chunks for speed.
 */
#define  SBLOCKSIZE 4096	/* default size of sb_data */
typedef struct sblock_S sblock_T;
struct sblock_S
{
    sblock_T	*sb_next;	/* next block in list */
    char_u	sb_data[1];	/* data, actually longer */
};

/* Structure to store words and additions.  Used twice : once for case-folded
 * and once for keep-case words. */
typedef struct winfo_S
{
    hashtab_T	wi_ht;		/* hashtable with all words, both dword_T and
				   nword_T (check flags for DW_NWORD) */
    garray_T	wi_add;		/* table with pointers to additions in a
				   dword_T */
    int		wi_addlen;	/* longest addition length */
} winfo_T;

/*
 * Structure used to store words and other info for one language.
 */
typedef struct slang_S slang_T;
struct slang_S
{
    slang_T	*sl_next;	/* next language */
    char_u	sl_name[2];	/* language name "en", "nl", etc. */
    winfo_T	sl_fwords;	/* case-folded words and additions */
    winfo_T	sl_kwords;	/* keep-case words and additions */
    char_u	sl_regions[17];	/* table with up to 8 region names plus NUL */
    sblock_T	*sl_block;	/* list with allocated memory blocks */
};

static slang_T *first_lang = NULL;

/* Entry for dword in "sl_ht".  Also used for part of an nword, starting with
 * the first non-word character.  And used for additions in wi_add. */
typedef struct dword_S
{
    char_u	dw_region;	/* one bit per region where it's valid */
    char_u	dw_flags;	/* DW_ flags */
    char_u	dw_word[1];	/* actually longer, NUL terminated */
} dword_T;

#define REGION_ALL 0xff

#define HI2DWORD(hi) (dword_T *)(hi->hi_key - 2)

/* Entry for a nword in "sl_ht".  Note that the last three items must be
 * identical to dword_T, so that they can be in the same hashtable. */
typedef struct nword_S
{
    garray_T	nw_ga;		/* table with pointers to dword_T for part
				   starting with non-word character */
    int		nw_maxlen;	/* longest nword length (after the dword) */
    char_u	nw_region;	/* one bit per region where it's valid */
    char_u	nw_flags;	/* DW_ flags */
    char_u	nw_word[1];	/* actually longer, NUL terminated */
} nword_T;

/* Get nword_T pointer from hashitem that uses nw_word */
static nword_T dumnw;
#define HI2NWORD(hi)	((nword_T *)((hi)->hi_key - (dumnw.nw_word - (char_u *)&dumnw)))

#define DW_CAP	    0x01	/* word must start with capital */
#define DW_RARE	    0x02	/* rare word */
#define DW_NWORD    0x04	/* this is an nword_T */
#define DW_DWORD    0x08	/* (also) use as dword without nword */

/*
 * Structure used in "b_langp", filled from 'spelllang'.
 */
typedef struct langp_S
{
    slang_T	*lp_slang;	/* info for this language (NULL for last one) */
    int		lp_region;	/* bitmask for region or REGION_ALL */
} langp_T;

#define LANGP_ENTRY(ga, i)	(((langp_T *)(ga).ga_data) + (i))
#define DWORD_ENTRY(gap, i)	*(((dword_T **)(gap)->ga_data) + i)

#define SP_OK		0
#define SP_BAD		1
#define SP_RARE		2
#define SP_LOCAL	3

static char *e_invchar2 = N_("E753: Invalid character in \"%s\"");

static slang_T *spell_load_lang __ARGS((char_u *lang));
static void spell_load_file __ARGS((char_u *fname));
static int find_region __ARGS((char_u *rp, char_u *region));

/*
 * Main spell-checking function.
 * "ptr" points to the start of a word.
 * "*attrp" is set to the attributes for a badly spelled word.  For a non-word
 * or when it's OK it remains unchanged.
 * This must only be called when 'spelllang' is not empty.
 * Returns the length of the word in bytes, also when it's OK, so that the
 * caller can skip over the word.
 */
    int
spell_check(wp, ptr, attrp)
    win_T	*wp;		/* current window */
    char_u	*ptr;
    int		*attrp;
{
    char_u	*e;		/* end of word */
    char_u	*ne;		/* new end of word */
    char_u	*me;		/* max. end of match */
    langp_T	*lp;
    int		result;
    int		len = 0;
    hashitem_T	*hi;
    int		round;
    char_u	kword[MAXWLEN + 1];	/* word copy */
    char_u	fword[MAXWLEN + 1];	/* word with case folded */
    char_u	match[MAXWLEN + 1];	/* fword with additional chars */
    char_u	kwordclen[MAXWLEN + 1];	/* len of orig chars after kword[] */
    char_u	fwordclen[MAXWLEN + 1]; /* len of chars after fword[] */
    char_u	*clen;
    int		cidx = 0;		/* char index in xwordclen[] */
    hash_T	fhash;			/* hash for fword */
    hash_T	khash;			/* hash for kword */
    int		match_len = 0;		/* length of match[] */
    int		fmatch_len = 0;		/* length of nword match in chars */
    garray_T	*gap;
    int		l, t;
    char_u	*p, *tp;
    int		n;
    dword_T	*dw;
    dword_T	*tdw;
    winfo_T	*wi;
    nword_T	*nw;
    int		w_isupper;

    /* Find the end of the word.  We already know that *ptr is a word char. */
    e = ptr;
    do
    {
	mb_ptr_adv(e);
	++len;
    } while (*e != NUL && spell_iswordc(e));

    /* A word starting with a number is always OK. */
    if (*ptr >= '0' && *ptr <= '9')
	return (int)(e - ptr);

#ifdef FEAT_MBYTE
    w_isupper = MB_ISUPPER(mb_ptr2char(ptr));
#else
    w_isupper = MB_ISUPPER(*ptr);
#endif

    /* Make a copy of the word so that it can be NUL terminated.
     * Compute hash value. */
    mch_memmove(kword, ptr, e - ptr);
    kword[e - ptr] = NUL;
    khash = hash_hash(kword);

    /* Make case-folded copy of the Word.  Compute its hash value. */
    (void)str_foldcase(ptr, e - ptr, fword, MAXWLEN + 1);
    fhash = hash_hash(fword);

    /* Further case-folded characters to check for an nword match go in
     * match[]. */
    me = e;

    /* "ne" is the end for the longest match */
    ne = e;

    /* The word is bad unless we find it in the dictionary. */
    result = SP_BAD;

    /*
     * Loop over the languages specified in 'spelllang'.
     * We check them all, because a matching nword may be longer than an
     * already found dword or nword.
     */
    for (lp = LANGP_ENTRY(wp->w_buffer->b_langp, 0); lp->lp_slang != NULL; ++lp)
    {
	/*
	 * Check for a matching word in the hashtable.
	 * Check both the keep-case word and the fold-case word.
	 */
	for (round = 0; round <= 1; ++round)
	{
	    if (round == 0)
	    {
		wi = &lp->lp_slang->sl_kwords;
		hi = hash_lookup(&wi->wi_ht, kword, khash);
	    }
	    else
	    {
		wi = &lp->lp_slang->sl_fwords;
		hi = hash_lookup(&wi->wi_ht, fword, fhash);
	    }
	    if (!HASHITEM_EMPTY(hi))
	    {
		/*
		 * If this is an nword entry, check for match with remainder.
		 */
		dw = HI2DWORD(hi);
		if (dw->dw_flags & DW_NWORD)
		{
		    /* If the word is not defined as a dword we must find an
		     * nword. */
		    if ((dw->dw_flags & DW_DWORD) == 0)
			dw = NULL;

		    /* Fold more characters when needed for the nword.  Need
		     * to do one extra to check for a non-word character after
		     * the nword.  Also keep the byte-size of each character,
		     * both before and after folding case. */
		    nw = HI2NWORD(hi);
		    while ((round == 0
				? me - e <= nw->nw_maxlen
				: match_len <= nw->nw_maxlen)
			    && *me != NUL)
		    {
#ifdef FEAT_MBYTE
			l = mb_ptr2len_check(me);
#else
			l = 1;
#endif
			(void)str_foldcase(me, l, match + match_len,
						     MAXWLEN - match_len + 1);
			me += l;
			kwordclen[cidx] = l;
			fwordclen[cidx] = STRLEN(match + match_len);
			match_len += fwordclen[cidx];
			++cidx;
		    }

		    if (round == 0)
		    {
			clen = kwordclen;
			tp = e;
		    }
		    else
		    {
			clen = fwordclen;
			tp = match;
		    }

		    /* Match with each item.  The longest match wins:
		     * "you've" is longer than "you". */
		    gap = &nw->nw_ga;
		    for (t = 0; t < gap->ga_len; ++t)
		    {
			/* Skip entries with wrong case for first char.
			 * Continue if it's a rare word without a captial. */
			tdw = DWORD_ENTRY(gap, t);
			if ((tdw->dw_flags & (DW_CAP | DW_RARE)) == DW_CAP
								&& !w_isupper)
			    continue;

			p = tdw->dw_word;
			l = 0;
			for (n = 0; p[n] != 0; n += clen[l++])
			    if (vim_memcmp(p + n, tp + n, clen[l]) != 0)
				break;

			/* Use a match if it's longer than previous matches
			 * and the next character is not a word character. */
			if (p[n] == 0 && l > fmatch_len && (tp[n] == 0
						   || !spell_iswordc(tp + n)))
			{
			    dw = tdw;
			    fmatch_len = l;
			    if (round == 0)
				ne = tp + n;
			    else
			    {
				/* Need to use the length of the original
				 * chars, not the fold-case ones. */
				ne = e;
				for (l = 0; l < fmatch_len; ++l)
				    ne += kwordclen[l];
			    }
			    if ((lp->lp_region & tdw->dw_region) == 0)
				result = SP_LOCAL;
			    else if ((tdw->dw_flags & DW_CAP) && !w_isupper)
				result = SP_RARE;
			    else
				result = SP_OK;
			}
		    }

		}

		if (dw != NULL)
		{
		    if (dw->dw_flags & DW_CAP)
		    {
			/* Need to check first letter is uppercase.  If it is,
			 * check region.  If it isn't it may be a rare word.
			 * */
			if (w_isupper)
			{
			    if ((dw->dw_region & lp->lp_region) == 0)
				result = SP_LOCAL;
			    else
				result = SP_OK;
			}
			else if (dw->dw_flags & DW_RARE)
			    result = SP_RARE;
		    }
		    else
		    {
			if ((dw->dw_region & lp->lp_region) == 0)
			    result = SP_LOCAL;
			else if (dw->dw_flags & DW_RARE)
			    result = SP_RARE;
			else
			    result = SP_OK;
		    }
		}
	    }
	}

	/*
	 * Check for an addition.
	 * Only after a dword, not after an nword.
	 * Check both the keep-case word and the fold-case word.
	 */
	if (fmatch_len == 0)
	    for (round = 0; round <= 1; ++round)
	    {
		if (round == 0)
		    wi = &lp->lp_slang->sl_kwords;
		else
		    wi = &lp->lp_slang->sl_fwords;
		gap = &wi->wi_add;
		if (gap->ga_len == 0)   /* no additions, skip quickly */
		    continue;

		/* Fold characters when needed for the addition.  Need to do one
		 * extra to check for a word character after the addition. */
		while ((round == 0
			    ? me - e <= wi->wi_addlen
			    : match_len <= wi->wi_addlen)
			&& *me != NUL)
		{
#ifdef FEAT_MBYTE
		    l = mb_ptr2len_check(me);
#else
		    l = 1;
#endif
		    (void)str_foldcase(me, l, match + match_len,
							 MAXWLEN - match_len + 1);
		    me += l;
		    kwordclen[cidx] = l;
		    fwordclen[cidx] = STRLEN(match + match_len);
		    match_len += fwordclen[cidx];
		    ++cidx;
		}

		if (round == 0)
		{
		    clen = kwordclen;
		    tp = e;
		}
		else
		{
		    clen = fwordclen;
		    tp = match;
		}

		/* Addition lookup.  Uses a linear search, there should be
		 * very few.  If there is a match adjust "ne" to the end.
		 * This doesn't change whether a word was good or bad, only
		 * the length. */
		for (t = 0; t < gap->ga_len; ++t)
		{
		    tdw = DWORD_ENTRY(gap, t);
		    p = tdw->dw_word;
		    l = 0;
		    for (n = 0; p[n] != 0; n += clen[l++])
			if (vim_memcmp(p + n, tp + n, clen[l]) != 0)
			    break;

		    /* Use a match if it's longer than previous matches
		     * and the next character is not a word character. */
		    if (p[n] == 0 && l > fmatch_len
				    && (tp[n] == 0 || !spell_iswordc(tp + n)))
		    {
			fmatch_len = l;
			if (round == 0)
			    ne = tp + n;
			else
			{
			    /* Need to use the length of the original
			     * chars, not the fold-case ones. */
			    ne = e;
			    for (l = 0; l < fmatch_len; ++l)
				ne += kwordclen[l];
			}
		    }
		}
	    }
    }

    if (result != SP_OK)
    {
	if (result == SP_BAD)
	    *attrp = highlight_attr[HLF_SPB];
	else if (result == SP_RARE)
	    *attrp = highlight_attr[HLF_SPR];
	else
	    *attrp = highlight_attr[HLF_SPL];
    }

    return (int)(ne - ptr);
}

static slang_T	    *load_lp;	/* passed from spell_load_lang() to
				   spell_load_file() */

/*
 * Load language "lang[2]".
 */
    static slang_T *
spell_load_lang(lang)
    char_u	*lang;
{
    slang_T	*lp;
    char_u	fname_enc[80];
    char_u	fname_ascii[20];
    char_u	*p;
    int		r;

    lp = (slang_T *)alloc(sizeof(slang_T));
    if (lp != NULL)
    {
	lp->sl_name[0] = lang[0];
	lp->sl_name[1] = lang[1];
	hash_init(&lp->sl_fwords.wi_ht);
	ga_init2(&lp->sl_fwords.wi_add, sizeof(dword_T *), 4);
	lp->sl_fwords.wi_addlen = 0;
	hash_init(&lp->sl_kwords.wi_ht);
	ga_init2(&lp->sl_kwords.wi_add, sizeof(dword_T *), 4);
	lp->sl_kwords.wi_addlen = 0;
	lp->sl_regions[0] = NUL;
	lp->sl_block = NULL;

	/* Find all spell files for "lang" in 'runtimepath' and load them.
	 * Use 'encoding', except that we use "latin1" for "latin9". */
#ifdef FEAT_MBYTE
	if (STRLEN(p_enc) < 60 && STRCMP(p_enc, "iso-8859-15") != 0)
	    p = p_enc;
	else
#endif
	    p = (char_u *)"latin1";
	load_lp = lp;
	sprintf((char *)fname_enc, "spell/%c%c.%s.spl", lang[0], lang[1], p);
	r = do_in_runtimepath(fname_enc, TRUE, spell_load_file);
	if (r == FAIL)
	{
	    /* Try again to find an ASCII spell file. */
	    sprintf((char *)fname_ascii, "spell/%c%c.spl", lang[0], lang[1]);
	    r = do_in_runtimepath(fname_ascii, TRUE, spell_load_file);
	}

	if (r == FAIL)
	{
	    vim_free(lp);
	    lp = NULL;
	    smsg((char_u *)_("Warning: Cannot find dictionary \"%s\""),
							       fname_enc + 6);
	}
	else
	{
	    lp->sl_next = first_lang;
	    first_lang = lp;
	}
    }

    return lp;
}

/*
 * Load one spell file into "load_lp".
 * Invoked through do_in_runtimepath().
 */
    static void
spell_load_file(fname)
    char_u	*fname;
{
    int		fd;
    size_t	len;
    int		l;
    char_u	*p = NULL, *np;
    sblock_T	*bl = NULL;
    int		bl_used = 0;
    size_t	rest = 0;
    char_u	*rbuf;		/* read buffer */
    char_u	*rbuf_end;	/* past last valid char in "rbuf" */
    hash_T	hash;
    hashitem_T	*hi;
    int		c;
    int		cc;
    int		region = REGION_ALL;
    int		wlen;
    winfo_T	*wi;
    dword_T	*dw, *edw = NULL;
    nword_T	*nw = NULL;
    int		flags;
    char_u	*save_sourcing_name = sourcing_name;
    linenr_T	save_sourcing_lnum = sourcing_lnum;

    rbuf = alloc((unsigned)(SBLOCKSIZE + MAXWLEN + 1));
    if (rbuf == NULL)
	return;

    fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
    if (fd < 0)
    {
	EMSG2(_(e_notopen), fname);
	goto theend;
    }

    sourcing_name = fname;
    sourcing_lnum = 0;

    /* Get the length of the whole file. */
    len = lseek(fd, (off_t)0, SEEK_END);
    lseek(fd, (off_t)0, SEEK_SET);

    /*
     * Read the file one block at a time.
     * "rest" is the length of an incomplete line at the previous block.
     * "p" points to the remainder.
     */
    while (len > 0)
    {
	/* Read a block from the file.  Prepend the remainder of the previous
	 * block, if any. */
	if (rest > 0)
	{
	    if (rest > MAXWLEN)	    /* truncate long line (should be comment) */
		rest = MAXWLEN;
	    mch_memmove(rbuf, p, rest);
	    --sourcing_lnum;
	}
	if (len > SBLOCKSIZE)
	    l = SBLOCKSIZE;
	else
	    l = len;
	len -= l;
	if (read(fd, rbuf + rest, l) != l)
	{
	    EMSG2(_(e_notread), fname);
	    break;
	}
	rbuf_end = rbuf + l + rest;
	rest = 0;

	/* Deal with each line that was read until we finish the block. */
	for (p = rbuf; p < rbuf_end; p = np)
	{
	    ++sourcing_lnum;

	    /* "np" points to the first char after the line (CR, NL or white
	     * space). */
	    for (np = p; np < rbuf_end && *np >= ' '; mb_ptr_adv(np))
		;
	    if (np >= rbuf_end)
	    {
		/* Incomplete line or end of file. */
		rest = np - p;
		if (len == 0)
		    EMSG(_("E751: Truncated spell file"));
		break;
	    }
	    *np = NUL;	    /* terminate the line with a NUL */

	    if (*p == '-')
	    {
		/*
		 * Region marker: ---, -xx, -xx-yy, etc.
		 */
		++p;
		if (*p == '-')
		{
		    if (p[1] != '-' || p[2] != NUL)
		    {
			EMSG2(_(e_invchar2), p - 1);
			len = 0;
			break;
		    }
		    region = REGION_ALL;
		}
		else
		{
		    char_u	*rp = load_lp->sl_regions;
		    int		r;

		    /* Start of a region.  The region may be repeated:
		     * "-ca-uk".  Fill "region" with the bit mask for the
		     * ones we find. */
		    region = 0;
		    for (;;)
		    {
			r = find_region(rp, p);
			if (r == REGION_ALL)
			{
			    /* new region, add it to sl_regions[] */
			    r = STRLEN(rp);
			    if (r >= 16)
			    {
				EMSG2(_("E752: Too many regions: %s"), p);
				len = 0;
				break;
			    }
			    else
			    {
				rp[r] = p[0];
				rp[r + 1] = p[1];
				rp[r + 2] = NUL;
				r = 1 << (r / 2);
			    }
			}
			else
			    r = 1 << r;

			region |= r;
			if (p[2] != '-')
			{
			    if (p[2] > ' ')
			    {
				EMSG2(_(e_invchar2), p - 1);
				len = 0;
			    }
			    break;
			}
			p += 3;
		    }
		}
	    }
	    else if (*p != '#' && *p != NUL)
	    {
		/*
		 * Not an empty line or comment.
		 */
		if (*p == '!')
		{
		    wi = &load_lp->sl_kwords;	    /* keep case */
		    ++p;
		}
		else
		    wi = &load_lp->sl_fwords;	    /* fold case */

		flags = 0;
		c = *p;
		if (c == '>')		/* rare word */
		{
		    flags = DW_RARE;
		    ++p;
		}
		else if (*p == '+')	/* addition */
		    ++p;

		if (c != '+' && !spell_iswordc(p))
		{
		    EMSG2(_(e_invchar2), p);
		    len = 0;
		    break;
		}

		/* Make sure there is room for the word.  Folding case may
		 * double the size. */
		wlen = np - p;
		if (bl == NULL || bl_used + sizeof(dword_T) + wlen
#ifdef FEAT_MBYTE
					    * (has_mbyte ? 2 : 1)
#endif
							    >= SBLOCKSIZE)
		{
		    /* Allocate a block of memory to store the dword_T in.
		     * This is not freed until spell_reload() is called. */
		    bl = (sblock_T *)alloc((unsigned)(sizeof(sblock_T)
							   + SBLOCKSIZE));
		    if (bl == NULL)
		    {
			len = 0;
			break;
		    }
		    bl->sb_next = load_lp->sl_block;
		    load_lp->sl_block = bl;
		    bl_used = 0;
		}
		dw = (dword_T *)(bl->sb_data + bl_used);

		/* For fold-case words fold the case and check for start
		 * with uppercase letter. */
		if (wi == &load_lp->sl_fwords)
		{
#ifdef FEAT_MBYTE
		    if (MB_ISUPPER(mb_ptr2char(p)))
#else
		    if (MB_ISUPPER(*p))
#endif
			flags |= DW_CAP;

		    /* Fold case. */
		    (void)str_foldcase(p, np - p, dw->dw_word, wlen
#ifdef FEAT_MBYTE
						     * (has_mbyte ? 2 : 1)
#endif
								     + 1);
#ifdef FEAT_MBYTE
		    /* case folding may change length of word */
		    wlen = STRLEN(dw->dw_word);
#endif
		}
		else
		{
		    /* Keep case: copy the word as-is. */
		    mch_memmove(dw->dw_word, p, wlen + 1);
		}

		if (c == '+')
		{
		    garray_T    *gap = &wi->wi_add;

		    /* Addition.  TODO: search for matching entry? */
		    if (wi->wi_addlen < wlen)
			wi->wi_addlen = wlen;
		    if (ga_grow(gap, 1) == FAIL)
		    {
			len = 0;
			break;
		    }
		    *(((dword_T **)gap->ga_data) + gap->ga_len) = dw;
		    ++gap->ga_len;
		    dw->dw_region = region;
		    dw->dw_flags = flags;
		    bl_used += sizeof(dword_T) + wlen;
		}
		else
		{
		    /*
		     * Check for a non-word character.  If found it's
		     * going to be an nword.
		     * For an nword we split in two: the leading dword and
		     * the remainder.  The dword goes in the hashtable
		     * with an nword_T, the remainder is put in the
		     * dword_T (starting with the first non-word
		     * character).
		     */
		    cc = NUL;
		    for (p = dw->dw_word; *p != NUL; mb_ptr_adv(p))
			if (!spell_iswordc(p))
			{
			    cc = *p;
			    *p = NUL;
			    break;
			}

		    /* check if we already have this dword */
		    hash = hash_hash(dw->dw_word);
		    hi = hash_lookup(&wi->wi_ht, dw->dw_word, hash);
		    if (!HASHITEM_EMPTY(hi))
		    {
			/* Existing entry. */
			edw = HI2DWORD(hi);
			if ((edw->dw_flags & (DW_CAP | DW_RARE))
				   == (dw->dw_flags & (DW_CAP | DW_RARE)))
			{
			    if (p_verbose > 0)
				smsg((char_u *)_("Warning: duplicate word \"%s\" in %s"),
						      dw->dw_word, fname);
			}
		    }

		    if (cc != NUL) /* nword */
		    {
			if (HASHITEM_EMPTY(hi)
				       || (edw->dw_flags & DW_NWORD) == 0)
			{
			    sblock_T *sb;

			    /* Need to allocate a new nword_T.  Put it in an
			     * sblock_T, so that we can free it later. */
			    sb = (sblock_T *)alloc(
				    (unsigned)(sizeof(sblock_T)
					       + sizeof(nword_T) + wlen));
			    if (sb == NULL)
			    {
				len = 0;
				break;
			    }
			    sb->sb_next = load_lp->sl_block;
			    load_lp->sl_block = sb;
			    nw = (nword_T *)sb->sb_data;

			    ga_init2(&nw->nw_ga, sizeof(dword_T *), 4);
			    nw->nw_maxlen = 0;
			    STRCPY(nw->nw_word, dw->dw_word);
			    if (!HASHITEM_EMPTY(hi))
			    {
				/* Note: the nw_region and nw_flags is for
				 * the dword that matches with the start
				 * of this nword, not for the nword
				 * itself! */
				nw->nw_region = edw->dw_region;
				nw->nw_flags = edw->dw_flags | DW_NWORD;

				/* Remove the dword item so that we can
				 * add it as an nword. */
				hash_remove(&wi->wi_ht, hi);
				hi = hash_lookup(&wi->wi_ht,
						       nw->nw_word, hash);
			    }
			    else
			    {
				nw->nw_region = 0;
				nw->nw_flags = DW_NWORD;
			    }
			}
			else
			    nw = HI2NWORD(hi);
		    }

		    if (HASHITEM_EMPTY(hi))
		    {
			/* Add new dword or nword entry. */
			hash_add_item(&wi->wi_ht, hi, cc == NUL
				       ? dw->dw_word : nw->nw_word, hash);
			if (cc == NUL)
			{
			    /* New dword: init the values and count the
			     * used space.  */
			    dw->dw_flags = DW_DWORD | flags;
			    dw->dw_region = region;
			    bl_used += sizeof(dword_T) + wlen;
			}
		    }
		    else if (cc == NUL)
		    {
			/* existing dword: add the region and flags */
			dw = edw;
			dw->dw_region |= region;
			dw->dw_flags |= DW_DWORD | flags;
		    }

		    if (cc != NUL)
		    {
			/* Use the dword for the non-word character and
			 * following characters. */
			dw->dw_region = region;
			dw->dw_flags = flags;
			STRCPY(dw->dw_word + 1, p + 1);
			dw->dw_word[0] = cc;
			l = wlen - (p - dw->dw_word);
			bl_used += sizeof(dword_T) + l;
			if (nw->nw_maxlen < l)
			    nw->nw_maxlen = l;

			/* Add the dword to the growarray in the nword. */
			if (ga_grow(&nw->nw_ga, 1) == FAIL)
			{
			    len = 0;
			    break;
			}
			*((dword_T **)nw->nw_ga.ga_data + nw->nw_ga.ga_len)
								     = dw;
			++nw->nw_ga.ga_len;
		    }
		}
	    }

	    /* Skip over CR and NL characters and trailing white space. */
	    while (np < rbuf_end && *np <= ' ')
		++np;
	}
    }

    close(fd);
theend:
    sourcing_name = save_sourcing_name;
    sourcing_lnum = save_sourcing_lnum;
    vim_free(rbuf);
}


#endif