summaryrefslogtreecommitdiff
path: root/tex/context/base/font-otn.lua
blob: b1bd4530478e55e9a1ebc44b65a69ac08ec7ee84 (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
if not modules then modules = { } end modules ['font-otn'] = {
    version   = 1.001,
    comment   = "companion to font-ini.mkiv",
    author    = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
    copyright = "PRAGMA ADE / ConTeXt Development Team",
    license   = "see context related readme files",
}

-- todo: looks like we have a leak somewhere (probably in ligatures)
-- todo: copy attributes to disc

-- this is a context version which can contain experimental code, but when we
-- have serious patches we also need to change the other two font-otn files

-- preprocessors = { "nodes" }

-- anchor class : mark, mkmk, curs, mklg (todo)
-- anchor type  : mark, basechar, baselig, basemark, centry, cexit, max (todo)

-- this is still somewhat preliminary and it will get better in due time;
-- much functionality could only be implemented thanks to the husayni font
-- of Idris Samawi Hamid to who we dedicate this module.

-- in retrospect it always looks easy but believe it or not, it took a lot
-- of work to get proper open type support done: buggy fonts, fuzzy specs,
-- special made testfonts, many skype sessions between taco, idris and me,
-- torture tests etc etc ... unfortunately the code does not show how much
-- time it took ...

-- todo:
--
-- extension infrastructure (for usage out of context)
-- sorting features according to vendors/renderers
-- alternative loop quitters
-- check cursive and r2l
-- find out where ignore-mark-classes went
-- default features (per language, script)
-- handle positions (we need example fonts)
-- handle gpos_single (we might want an extra width field in glyph nodes because adding kerns might interfere)
-- mark (to mark) code is still not what it should be (too messy but we need some more extreem husayni tests)
-- remove some optimizations (when I have a faster machine)
--
-- beware:
--
-- we do some disc jugling where we need to keep in mind that the
-- pre, post and replace fields can have prev pointers to a nesting
-- node ... i wonder if that is still needed
--
-- not possible:
--
-- \discretionary {alpha-} {betagammadelta}
--   {\discretionary {alphabeta-} {gammadelta}
--      {\discretionary {alphabetagamma-} {delta}
--         {alphabetagammadelta}}}

--[[ldx--
<p>This module is a bit more split up that I'd like but since we also want to test
with plain <l n='tex'/> it has to be so. This module is part of <l n='context'/>
and discussion about improvements and functionality mostly happens on the
<l n='context'/> mailing list.</p>

<p>The specification of OpenType is kind of vague. Apart from a lack of a proper
free specifications there's also the problem that Microsoft and Adobe
may have their own interpretation of how and in what order to apply features.
In general the Microsoft website has more detailed specifications and is a
better reference. There is also some information in the FontForge help files.</p>

<p>Because there is so much possible, fonts might contain bugs and/or be made to
work with certain rederers. These may evolve over time which may have the side
effect that suddenly fonts behave differently.</p>

<p>After a lot of experiments (mostly by Taco, me and Idris) we're now at yet another
implementation. Of course all errors are mine and of course the code can be
improved. There are quite some optimizations going on here and processing speed
is currently acceptable. Not all functions are implemented yet, often because I
lack the fonts for testing. Many scripts are not yet supported either, but I will
look into them as soon as <l n='context'/> users ask for it.</p>

<p>Because there are different interpretations possible, I will extend the code
with more (configureable) variants. I can also add hooks for users so that they can
write their own extensions.</p>

<p>Glyphs are indexed not by unicode but in their own way. This is because there is no
relationship with unicode at all, apart from the fact that a font might cover certain
ranges of characters. One character can have multiple shapes. However, at the
<l n='tex'/> end we use unicode so and all extra glyphs are mapped into a private
space. This is needed because we need to access them and <l n='tex'/> has to include
then in the output eventually.</p>

<p>The raw table as it coms from <l n='fontforge'/> gets reorganized in to fit out needs.
In <l n='context'/> that table is packed (similar tables are shared) and cached on disk
so that successive runs can use the optimized table (after loading the table is
unpacked). The flattening code used later is a prelude to an even more compact table
format (and as such it keeps evolving).</p>

<p>This module is sparsely documented because it is a moving target. The table format
of the reader changes and we experiment a lot with different methods for supporting
features.</p>

<p>As with the <l n='afm'/> code, we may decide to store more information in the
<l n='otf'/> table.</p>

<p>Incrementing the version number will force a re-cache. We jump the number by one
when there's a fix in the <l n='fontforge'/> library or <l n='lua'/> code that
results in different tables.</p>
--ldx]]--

-- action                    handler     chainproc             chainmore              comment
--
-- gsub_single               ok          ok                    ok
-- gsub_multiple             ok          ok                    not implemented yet
-- gsub_alternate            ok          ok                    not implemented yet
-- gsub_ligature             ok          ok                    ok
-- gsub_context              ok          --
-- gsub_contextchain         ok          --
-- gsub_reversecontextchain  ok          --
-- chainsub                  --          ok
-- reversesub                --          ok
-- gpos_mark2base            ok          ok
-- gpos_mark2ligature        ok          ok
-- gpos_mark2mark            ok          ok
-- gpos_cursive              ok          untested
-- gpos_single               ok          ok
-- gpos_pair                 ok          ok
-- gpos_context              ok          --
-- gpos_contextchain         ok          --
--
-- todo: contextpos and contextsub and class stuff
--
-- actions:
--
-- handler   : actions triggered by lookup
-- chainproc : actions triggered by contextual lookup
-- chainmore : multiple substitutions triggered by contextual lookup (e.g. fij -> f + ij)
--
-- remark: the 'not implemented yet' variants will be done when we have fonts that use them

-- We used to have independent hashes for lookups but as the tags are unique
-- we now use only one hash. If needed we can have multiple again but in that
-- case I will probably prefix (i.e. rename) the lookups in the cached font file.

-- Todo: make plugin feature that operates on char/glyphnode arrays

local type, next, tonumber = type, next, tonumber
local random = math.random
local formatters = string.formatters

local logs, trackers, nodes, attributes = logs, trackers, nodes, attributes

local registertracker   = trackers.register
local registerdirective = directives.register

local fonts = fonts
local otf   = fonts.handlers.otf

local trace_lookups      = false  registertracker("otf.lookups",      function(v) trace_lookups      = v end)
local trace_singles      = false  registertracker("otf.singles",      function(v) trace_singles      = v end)
local trace_multiples    = false  registertracker("otf.multiples",    function(v) trace_multiples    = v end)
local trace_alternatives = false  registertracker("otf.alternatives", function(v) trace_alternatives = v end)
local trace_ligatures    = false  registertracker("otf.ligatures",    function(v) trace_ligatures    = v end)
local trace_contexts     = false  registertracker("otf.contexts",     function(v) trace_contexts     = v end)
local trace_marks        = false  registertracker("otf.marks",        function(v) trace_marks        = v end)
local trace_kerns        = false  registertracker("otf.kerns",        function(v) trace_kerns        = v end)
local trace_cursive      = false  registertracker("otf.cursive",      function(v) trace_cursive      = v end)
local trace_preparing    = false  registertracker("otf.preparing",    function(v) trace_preparing    = v end)
local trace_bugs         = false  registertracker("otf.bugs",         function(v) trace_bugs         = v end)
local trace_details      = false  registertracker("otf.details",      function(v) trace_details      = v end)
local trace_applied      = false  registertracker("otf.applied",      function(v) trace_applied      = v end)
local trace_steps        = false  registertracker("otf.steps",        function(v) trace_steps        = v end)
local trace_skips        = false  registertracker("otf.skips",        function(v) trace_skips        = v end)
local trace_directions   = false  registertracker("otf.directions",   function(v) trace_directions   = v end)

local trace_kernruns     = false  registertracker("otf.kernruns",     function(v) trace_kernruns     = v end)
local trace_discruns     = false  registertracker("otf.discruns",     function(v) trace_discruns     = v end)
local trace_compruns     = false  registertracker("otf.compruns",     function(v) trace_compruns     = v end)

local quit_on_no_replacement = true  -- maybe per font
local check_discretionaries  = true -- "trace"
local zwnjruns               = true

registerdirective("otf.zwnjruns",                 function(v) zwnjruns = v end)
registerdirective("otf.chain.quitonnoreplacement",function(value) quit_on_no_replacement = value end)


local report_direct   = logs.reporter("fonts","otf direct")
local report_subchain = logs.reporter("fonts","otf subchain")
local report_chain    = logs.reporter("fonts","otf chain")
local report_process  = logs.reporter("fonts","otf process")
local report_prepare  = logs.reporter("fonts","otf prepare")
local report_warning  = logs.reporter("fonts","otf warning")
local report_run      = logs.reporter("fonts","otf run")

registertracker("otf.verbose_chain", function(v) otf.setcontextchain(v and "verbose") end)
registertracker("otf.normal_chain",  function(v) otf.setcontextchain(v and "normal")  end)

registertracker("otf.replacements", "otf.singles,otf.multiples,otf.alternatives,otf.ligatures")
registertracker("otf.positions","otf.marks,otf.kerns,otf.cursive")
registertracker("otf.actions","otf.replacements,otf.positions")
registertracker("otf.injections","nodes.injections")

registertracker("*otf.sample","otf.steps,otf.actions,otf.analyzing")

local nuts               = nodes.nuts
local tonode             = nuts.tonode
local tonut              = nuts.tonut

local getfield           = nuts.getfield
local setfield           = nuts.setfield
local getnext            = nuts.getnext
local getprev            = nuts.getprev
local getid              = nuts.getid
local getattr            = nuts.getattr
local setattr            = nuts.setattr
local getprop            = nuts.getprop
local setprop            = nuts.setprop
local getfont            = nuts.getfont
local getsubtype         = nuts.getsubtype
local getchar            = nuts.getchar

local insert_node_before = nuts.insert_before
local insert_node_after  = nuts.insert_after
local delete_node        = nuts.delete
local remove_node        = nuts.remove
local copy_node          = nuts.copy
local copy_node_list     = nuts.copy_list
local find_node_tail     = nuts.tail
local flush_node_list    = nuts.flush_list
local free_node          = nuts.free
local end_of_math        = nuts.end_of_math
local traverse_nodes     = nuts.traverse
local traverse_id        = nuts.traverse_id

local setmetatableindex  = table.setmetatableindex

local zwnj               = 0x200C
local zwj                = 0x200D
local wildcard           = "*"
local default            = "dflt"

local nodecodes          = nodes.nodecodes
local whatcodes          = nodes.whatcodes
local glyphcodes         = nodes.glyphcodes
local disccodes          = nodes.disccodes

local glyph_code         = nodecodes.glyph
local glue_code          = nodecodes.glue
local disc_code          = nodecodes.disc
local whatsit_code       = nodecodes.whatsit
local math_code          = nodecodes.math

local dir_code           = whatcodes.dir
local localpar_code      = whatcodes.localpar

local discretionary_code = disccodes.discretionary
local regular_code       = disccodes.regular
local automatic_code     = disccodes.automatic

local ligature_code      = glyphcodes.ligature

local privateattribute   = attributes.private

-- Something is messed up: we have two mark / ligature indices, one at the injection
-- end and one here ... this is based on KE's patches but there is something fishy
-- there as I'm pretty sure that for husayni we need some connection (as it's much
-- more complex than an average font) but I need proper examples of all cases, not
-- of only some.

local a_state            = privateattribute('state')
local a_cursbase         = privateattribute('cursbase') -- to be checked, probably can go

local injections         = nodes.injections
local setmark            = injections.setmark
local setcursive         = injections.setcursive
local setkern            = injections.setkern
local setpair            = injections.setpair
local resetinjection     = injections.reset
local copyinjection      = injections.copy
local setligaindex       = injections.setligaindex
local getligaindex       = injections.getligaindex

local cursonce           = true

local fonthashes         = fonts.hashes
local fontdata           = fonthashes.identifiers

local otffeatures        = fonts.constructors.newfeatures("otf")
local registerotffeature = otffeatures.register

local onetimemessage     = fonts.loggers.onetimemessage or function() end

otf.defaultnodealternate = "none" -- first last

-- we share some vars here, after all, we have no nested lookups and less code

local tfmdata             = false
local characters          = false
local descriptions        = false
local resources           = false
local marks               = false
local currentfont         = false
local lookuptable         = false
local anchorlookups       = false
local lookuptypes         = false
local lookuptags          = false
local handlers            = { }
local rlmode              = 0
local featurevalue        = false

-- head is always a whatsit so we can safely assume that head is not changed

-- we use this for special testing and documentation

local checkstep       = (nodes and nodes.tracers and nodes.tracers.steppers.check)    or function() end
local registerstep    = (nodes and nodes.tracers and nodes.tracers.steppers.register) or function() end
local registermessage = (nodes and nodes.tracers and nodes.tracers.steppers.message)  or function() end

local function logprocess(...)
    if trace_steps then
        registermessage(...)
    end
    report_direct(...)
end

local function logwarning(...)
    report_direct(...)
end

local f_unicode = formatters["%U"]
local f_uniname = formatters["%U (%s)"]
local f_unilist = formatters["% t (% t)"]

local function gref(n) -- currently the same as in font-otb
    if type(n) == "number" then
        local description = descriptions[n]
        local name = description and description.name
        if name then
            return f_uniname(n,name)
        else
            return f_unicode(n)
        end
    elseif n then
        local num, nam = { }, { }
        for i=1,#n do
            local ni = n[i]
            if tonumber(ni) then -- later we will start at 2
                local di = descriptions[ni]
                num[i] = f_unicode(ni)
                nam[i] = di and di.name or "-"
            end
        end
        return f_unilist(num,nam)
    else
        return "<error in node mode tracing>"
    end
end

local function cref(kind,chainname,chainlookupname,lookupname,index) -- not in the mood to alias f_
    if index then
        return formatters["feature %a, chain %a, sub %a, lookup %a, index %a"](kind,chainname,chainlookupname,lookuptags[lookupname],index)
    elseif lookupname then
        return formatters["feature %a, chain %a, sub %a, lookup %a"](kind,chainname,chainlookupname,lookuptags[lookupname])
    elseif chainlookupname then
        return formatters["feature %a, chain %a, sub %a"](kind,lookuptags[chainname],lookuptags[chainlookupname])
    elseif chainname then
        return formatters["feature %a, chain %a"](kind,lookuptags[chainname])
    else
        return formatters["feature %a"](kind)
    end
end

local function pref(kind,lookupname)
    return formatters["feature %a, lookup %a"](kind,lookuptags[lookupname])
end

-- We can assume that languages that use marks are not hyphenated. We can also assume
-- that at most one discretionary is present.

-- We do need components in funny kerning mode but maybe I can better reconstruct then
-- as we do have the font components info available; removing components makes the
-- previous code much simpler. Also, later on copying and freeing becomes easier.
-- However, for arabic we need to keep them around for the sake of mark placement
-- and indices.

local function copy_glyph(g) -- next and prev are untouched !
    local components = getfield(g,"components")
    if components then
        setfield(g,"components",nil)
        local n = copy_node(g)
        copyinjection(n,g) -- we need to preserve the lig indices
        setfield(g,"components",components)
        return n
    else
        local n = copy_node(g)
        copyinjection(n,g) -- we need to preserve the lig indices
        return n
    end
end

-- temp here (context)

local function collapse_disc(start,next)
    local replace1 = getfield(start,"replace")
    local replace2 = getfield(next,"replace")
    if replace1 and replace2 then
        local pre2  = getfield(next,"pre")
        local post2 = getfield(next,"post")
        setfield(replace1,"prev",nil)
        if pre2 then
            local pre1 = getfield(start,"pre")
            if pre1 then
                flush_node_list(pre1)
            end
            local pre1  = copy_node_list(replace1)
            local tail1 = find_node_tail(pre1)
            setfield(tail1,"next",pre2)
            setfield(pre2,"prev",tail1)
            setfield(start,"pre",pre1)
            setfield(next,"pre",nil)
        else
            setfield(start,"pre",nil)
        end
        if post2 then
            local post1 = getfield(start,"post")
            if post1 then
                flush_node_list(post1)
            end
            setfield(start,"post",post2)
        else
            setfield(start,"post",nil)
        end
        local tail1 = find_node_tail(replace1)
        setfield(tail1,"next",replace2)
        setfield(replace2,"prev",tail1)
        setfield(start,"replace",replace1)
        setfield(next,"replace",nil)
        --
        local nextnext = getnext(next)
        setfield(nextnext,"prev",start)
        setfield(start,"next",nextnext)
        free_node(next)
    else
        -- maybe remove it
    end
end

-- start is a mark and we need to keep that one

local function markstoligature(kind,lookupname,head,start,stop,char)
    if start == stop and getchar(start) == char then
        return head, start
    else
        local prev = getprev(start)
        local next = getnext(stop)
        setfield(start,"prev",nil)
        setfield(stop,"next",nil)
        local base = copy_glyph(start)
        if head == start then
            head = base
        end
        resetinjection(base)
        setfield(base,"char",char)
        setfield(base,"subtype",ligature_code)
        setfield(base,"components",start)
        if prev then
            setfield(prev,"next",base)
        end
        if next then
            setfield(next,"prev",base)
        end
        setfield(base,"next",next)
        setfield(base,"prev",prev)
        return head, base
    end
end

-- The next code is somewhat complicated by the fact that some fonts can have ligatures made
-- from ligatures that themselves have marks. This was identified by Kai in for instance
-- arabtype:  KAF LAM SHADDA ALEF FATHA (0x0643 0x0644 0x0651 0x0627 0x064E). This becomes
-- KAF LAM-ALEF with a SHADDA on the first and a FATHA op de second component. In a next
-- iteration this becomes a KAF-LAM-ALEF with a SHADDA on the second and a FATHA on the
-- third component.

local function getcomponentindex(start)
    if getid(start) ~= glyph_code then
        return 0
    elseif getsubtype(start) == ligature_code then
        local i = 0
        local components = getfield(start,"components")
        while components do
            i = i + getcomponentindex(components)
            components = getnext(components)
        end
        return i
    elseif not marks[getchar(start)] then
        return 1
    else
        return 0
    end
end

local a_noligature     = attributes.private("noligature")
local prehyphenchar    = languages and languages.prehyphenchar
local posthyphenchar   = languages and languages.posthyphenchar
----- preexhyphenchar  = languages and languages.preexhyphenchar
----- postexhyphenchar = languages and languages.postexhyphenchar

if prehyphenchar then

    -- okay

elseif context then

    report_warning("no language support") os.exit()

else

    local newlang   = lang.new
    local getpre    = lang.prehyphenchar
    local getpost   = lang.posthyphenchar
 -- local getpreex  = lang.preexhyphenchar
 -- local getpostex = lang.postexhyphenchar

    prehyphenchar    = function(l) local l = newlang(l) return l and getpre   (l) or -1 end
    posthyphenchar   = function(l) local l = newlang(l) return l and getpost  (l) or -1 end
 -- preexhyphenchar  = function(l) local l = newlang(l) return l and getpreex (l) or -1 end
 -- postexhyphenchar = function(l) local l = newlang(l) return l and getpostex(l) or -1 end

end

local function addhyphens(template,pre,post)
    -- inserted by hyphenation algorithm
    local l = getfield(template,"lang")
    local p = prehyphenchar(l)
    if p and p > 0 then
        local c = copy_node(template)
        setfield(c,"char",p)
        if pre then
            local t = find_node_tail(pre)
            setfield(t,"next",c)
            setfield(c,"prev",t)
        else
            pre = c
        end
    end
    local p = posthyphenchar(l)
    if p and p > 0 then
        local c = copy_node(template)
        setfield(c,"char",p)
        if post then
            -- post has a prev nesting node .. alternatively we could
            local prev = getprev(post)
            setfield(c,"next",post)
            setfield(post,"prev",c)
            if prev then
                setfield(prev,"next",c)
                setfield(c,"prev",prev)
            end
        else
            post = c
        end
    end
    return pre, post
end

local function toligature(kind,lookupname,head,start,stop,char,markflag,discfound) -- brr head
    if getattr(start,a_noligature) == 1 then
        -- so we can do: e\noligature{ff}e e\noligature{f}fie (we only look at the first)
        return head, start
    end
    if start == stop and getchar(start) == char then
        resetinjection(start)
        setfield(start,"char",char)
        return head, start
    end
    -- needs testing (side effects):
    local components = getfield(base,"components")
    if components then
        flush_node_list(components)
    end
    --
    local prev = getprev(start)
    local next = getnext(stop)
    local comp = start
    setfield(start,"prev",nil)
    setfield(stop,"next",nil)
    local base = copy_glyph(start)
    if start == head then
        head = base
    end
    resetinjection(base)
    setfield(base,"char",char)
    setfield(base,"subtype",ligature_code)
    setfield(base,"components",comp) -- start can have components .. do we need to flush?
    if prev then
        setfield(prev,"next",base)
    end
    if next then
        setfield(next,"prev",base)
    end
    setfield(base,"next",next)
    setfield(base,"prev",prev)
    if not discfound then
        local deletemarks = markflag ~= "mark"
        local components = start
        local baseindex = 0
        local componentindex = 0
        local head = base
        local current = base
        -- first we loop over the glyphs in start .. stop
        while start do
            local char = getchar(start)
            if not marks[char] then
                baseindex = baseindex + componentindex
                componentindex = getcomponentindex(start)
            elseif not deletemarks then -- quite fishy
                setligaindex(start,baseindex + getligaindex(start,componentindex))
                if trace_marks then
                    logwarning("%s: keep mark %s, gets index %s",pref(kind,lookupname),gref(char),getligaindex(start))
                end
                local n = copy_node(start)
                copyinjection(n,start)
                head, current = insert_node_after(head,current,n) -- unlikely that mark has components
            elseif trace_marks then
                logwarning("%s: delete mark %s",pref(kind,lookupname),gref(char))
            end
            start = getnext(start)
        end
        -- we can have one accent as part of a lookup and another following
     -- local start = components -- was wrong (component scanning was introduced when more complex ligs in devanagari was added)
        local start = getnext(current)
        while start and getid(start) == glyph_code do
            local char = getchar(start)
            if marks[char] then
                setligaindex(start,baseindex + getligaindex(start,componentindex))
                if trace_marks then
                    logwarning("%s: set mark %s, gets index %s",pref(kind,lookupname),gref(char),getligaindex(start))
                end
            else
                break
            end
            start = getnext(start)
        end
    else
        -- discfound ... forget about marks .. probably no scripts that hyphenate and have marks
        local discprev = getfield(discfound,"prev")
        local discnext = getfield(discfound,"next")
        if discprev and discnext then
            local subtype = getsubtype(discfound)
            if subtype == discretionary_code then
                local pre     = getfield(discfound,"pre")
                local post    = getfield(discfound,"post")
                local replace = getfield(discfound,"replace")
                if not replace then -- todo: signal simple hyphen
                    local prev = getfield(base,"prev")
                    local copied = copy_node_list(comp)
                    setfield(discnext,"prev",nil) -- also blocks funny assignments
                    setfield(discprev,"next",nil) -- also blocks funny assignments
                    if pre then
                        setfield(comp,"next",pre)
                        setfield(pre,"prev",comp)
                    end
                    pre = comp
                    if post then
                        local tail = find_node_tail(post)
                        setfield(tail,"next",discnext)
                        setfield(discnext,"prev",tail)
                        setfield(post,"prev",nil)
                    else
                        post = discnext
                    end
                    setfield(prev,"next",discfound)
                    setfield(next,"prev",discfound)
                    setfield(discfound,"next",next)
                    setfield(discfound,"prev",prev)
                    setfield(base,"next",nil)
                    setfield(base,"prev",nil)
                    setfield(base,"components",copied)
                    setfield(discfound,"pre",pre)
                    setfield(discfound,"post",post)
                    setfield(discfound,"replace",base)
                    setfield(discfound,"subtype",discretionary_code)
                    base = prev -- restart
                end
            elseif discretionary_code == regular_code then
             -- local prev   = getfield(base,"prev")
             -- local next   = getfield(base,"next")
                local copied = copy_node_list(comp)
                setfield(discnext,"prev",nil) -- also blocks funny assignments
                setfield(discprev,"next",nil) -- also blocks funny assignments
                local pre, post = addhyphens(comp,comp,discnext,subtype) -- takes from components
                setfield(prev,"next",discfound)
                setfield(next,"prev",discfound)
                setfield(discfound,"next",next)
                setfield(discfound,"prev",prev)
                setfield(base,"next",nil)
                setfield(base,"prev",nil)
                setfield(base,"components",copied)
                setfield(discfound,"pre",pre)
                setfield(discfound,"post",post)
                setfield(discfound,"replace",base)
                setfield(discfound,"subtype",discretionary_code)
                base = next -- or restart
            else
                -- forget about it in generic usage
            end
        end
    end
    return head, base
end

function handlers.gsub_single(head,start,kind,lookupname,replacement)
    if trace_singles then
        logprocess("%s: replacing %s by single %s",pref(kind,lookupname),gref(getchar(start)),gref(replacement))
    end
    resetinjection(start)
    setfield(start,"char",replacement)
    return head, start, true
end

local function get_alternative_glyph(start,alternatives,value,trace_alternatives)
    local n = #alternatives
    if value == "random" then
        local r = random(1,n)
        return alternatives[r], trace_alternatives and formatters["value %a, taking %a"](value,r)
    elseif value == "first" then
        return alternatives[1], trace_alternatives and formatters["value %a, taking %a"](value,1)
    elseif value == "last" then
        return alternatives[n], trace_alternatives and formatters["value %a, taking %a"](value,n)
    else
        value = tonumber(value)
        if type(value) ~= "number" then
            return alternatives[1], trace_alternatives and formatters["invalid value %s, taking %a"](value,1)
        elseif value > n then
            local defaultalt = otf.defaultnodealternate
            if defaultalt == "first" then
                return alternatives[n], trace_alternatives and formatters["invalid value %s, taking %a"](value,1)
            elseif defaultalt == "last" then
                return alternatives[1], trace_alternatives and formatters["invalid value %s, taking %a"](value,n)
            else
                return false, trace_alternatives and formatters["invalid value %a, %s"](value,"out of range")
            end
        elseif value == 0 then
            return getchar(start), trace_alternatives and formatters["invalid value %a, %s"](value,"no change")
        elseif value < 1 then
            return alternatives[1], trace_alternatives and formatters["invalid value %a, taking %a"](value,1)
        else
            return alternatives[value], trace_alternatives and formatters["value %a, taking %a"](value,value)
        end
    end
end

local function multiple_glyphs(head,start,multiple,ignoremarks)
    local nofmultiples = #multiple
    if nofmultiples > 0 then
        resetinjection(start)
        setfield(start,"char",multiple[1])
        if nofmultiples > 1 then
            local sn = getnext(start)
            for k=2,nofmultiples do -- todo: use insert_node
-- untested:
--
-- while ignoremarks and marks[getchar(sn)] then
--     local sn = getnext(sn)
-- end
                local n = copy_node(start) -- ignore components
                resetinjection(n)
                setfield(n,"char",multiple[k])
                setfield(n,"next",sn)
                setfield(n,"prev",start)
                if sn then
                    setfield(sn,"prev",n)
                end
                setfield(start,"next",n)
                start = n
            end
        end
        return head, start, true
    else
        if trace_multiples then
            logprocess("no multiple for %s",gref(getchar(start)))
        end
        return head, start, false
    end
end

function handlers.gsub_alternate(head,start,kind,lookupname,alternative,sequence)
    local value = featurevalue == true and tfmdata.shared.features[kind] or featurevalue
    local choice, comment = get_alternative_glyph(start,alternative,value,trace_alternatives)
    if choice then
        if trace_alternatives then
            logprocess("%s: replacing %s by alternative %a to %s, %s",pref(kind,lookupname),gref(getchar(start)),choice,gref(choice),comment)
        end
        resetinjection(start)
        setfield(start,"char",choice)
    else
        if trace_alternatives then
            logwarning("%s: no variant %a for %s, %s",pref(kind,lookupname),value,gref(getchar(start)),comment)
        end
    end
    return head, start, true
end

function handlers.gsub_multiple(head,start,kind,lookupname,multiple,sequence)
    if trace_multiples then
        logprocess("%s: replacing %s by multiple %s",pref(kind,lookupname),gref(getchar(start)),gref(multiple))
    end
    return multiple_glyphs(head,start,multiple,sequence.flags[1])
end

function handlers.gsub_ligature(head,start,kind,lookupname,ligature,sequence)
    local s, stop = getnext(start), nil
    local startchar = getchar(start)
    if marks[startchar] then
        while s do
            local id = getid(s)
            if id == glyph_code and getfont(s) == currentfont and getsubtype(s)<256 then
                local lg = ligature[getchar(s)]
                if lg then
                    stop = s
                    ligature = lg
                    s = getnext(s)
                else
                    break
                end
            else
                break
            end
        end
        if stop then
            local lig = ligature.ligature
            if lig then
                if trace_ligatures then
                    local stopchar = getchar(stop)
                    head, start = markstoligature(kind,lookupname,head,start,stop,lig)
                    logprocess("%s: replacing %s upto %s by ligature %s case 1",pref(kind,lookupname),gref(startchar),gref(stopchar),gref(getchar(start)))
                else
                    head, start = markstoligature(kind,lookupname,head,start,stop,lig)
                end
                return head, start, true, false
            else
                -- ok, goto next lookup
            end
        end
    else
        local skipmark  = sequence.flags[1]
        local discfound = false
        local lastdisc  = nil
        while s do
            local id = getid(s)
            if id == glyph_code and getsubtype(s)<256 then -- not needed
                if getfont(s) == currentfont then          -- also not needed only when mark
                    local char = getchar(s)
                    if skipmark and marks[char] then
                        s = getnext(s)
                    else -- ligature is a tree
                        local lg = ligature[char] -- can there be multiple in a row? maybe in a bad font
                        if lg then
                            if not discfound and lastdisc then
                                discfound = lastdisc
                                lastdisc  = nil
                            end
                            stop = s -- needed for fake so outside then
                            ligature = lg
                            s = getnext(s)
                        else
                            break
                        end
                    end
                else
                    break
                end
            elseif id == disc_code then
                lastdisc = s
                s = getnext(s)
            else
                break
            end
        end
        local lig = ligature.ligature -- can't we get rid of this .ligature?
        if lig then
            if stop then
                if trace_ligatures then
                    local stopchar = getchar(stop)
                    head, start = toligature(kind,lookupname,head,start,stop,lig,skipmark,discfound)
                    logprocess("%s: replacing %s upto %s by ligature %s case 2",pref(kind,lookupname),gref(startchar),gref(stopchar),gref(getchar(start)))
                else
                    head, start = toligature(kind,lookupname,head,start,stop,lig,skipmark,discfound)
                end
            else
                -- weird but happens (in some arabic font)
                resetinjection(start)
                setfield(start,"char",lig)
                if trace_ligatures then
                    logprocess("%s: replacing %s by (no real) ligature %s case 3",pref(kind,lookupname),gref(startchar),gref(lig))
                end
            end
            return head, start, true, discfound
        else
            -- weird but happens, pseudo ligatures ... just the components
        end
    end
    return head, start, false, discfound
end

-- function is_gsub_ligature(start,ligature) -- limited case: in disc nodes, only latin, always glyphs
--     local s = getnext(start)
--     while s do
--         local lg = ligature[getchar(s)]
--         if lg then
--             ligature = lg
--             s = getnext(s)
--         else
--             return
--         end
--     end
--     return ligature and ligature.ligature
-- end

--[[ldx--
<p>We get hits on a mark, but we're not sure if the it has to be applied so
we need to explicitly test for basechar, baselig and basemark entries.</p>
--ldx]]--

function handlers.gpos_mark2base(head,start,kind,lookupname,markanchors,sequence)
    local markchar = getchar(start)
    if marks[markchar] then
        local base = getprev(start) -- [glyph] [start=mark]
        if base and getid(base) == glyph_code and getfont(base) == currentfont and getsubtype(base)<256 then
            local basechar = getchar(base)
            if marks[basechar] then
                while true do
                    base = getprev(base)
                    if base and getid(base) == glyph_code and getfont(base) == currentfont and getsubtype(base)<256 then
                        basechar = getchar(base)
                        if not marks[basechar] then
                            break
                        end
                    else
                        if trace_bugs then
                            logwarning("%s: no base for mark %s",pref(kind,lookupname),gref(markchar))
                        end
                        return head, start, false
                    end
                end
            end
            local baseanchors = descriptions[basechar]
            if baseanchors then
                baseanchors = baseanchors.anchors
            end
            if baseanchors then
                local baseanchors = baseanchors['basechar']
                if baseanchors then
                    local al = anchorlookups[lookupname]
                    for anchor,ba in next, baseanchors do
                        if al[anchor] then
                            local ma = markanchors[anchor]
                            if ma then
                                local dx, dy, bound = setmark(start,base,tfmdata.parameters.factor,rlmode,ba,ma,characters[basechar])
                                if trace_marks then
                                    logprocess("%s, anchor %s, bound %s: anchoring mark %s to basechar %s => (%p,%p)",
                                        pref(kind,lookupname),anchor,bound,gref(markchar),gref(basechar),dx,dy)
                                end
                                return head, start, true
                            end
                        end
                    end
                    if trace_bugs then
                        logwarning("%s, no matching anchors for mark %s and base %s",pref(kind,lookupname),gref(markchar),gref(basechar))
                    end
                end
            elseif trace_bugs then
            --  logwarning("%s: char %s is missing in font",pref(kind,lookupname),gref(basechar))
                onetimemessage(currentfont,basechar,"no base anchors",report_fonts)
            end
        elseif trace_bugs then
            logwarning("%s: prev node is no char",pref(kind,lookupname))
        end
    elseif trace_bugs then
        logwarning("%s: mark %s is no mark",pref(kind,lookupname),gref(markchar))
    end
    return head, start, false
end

function handlers.gpos_mark2ligature(head,start,kind,lookupname,markanchors,sequence)
    -- check chainpos variant
    local markchar = getchar(start)
    if marks[markchar] then
        local base = getprev(start) -- [glyph] [optional marks] [start=mark]
        if base and getid(base) == glyph_code and getfont(base) == currentfont and getsubtype(base)<256 then
            local basechar = getchar(base)
            if marks[basechar] then
                while true do
                    base = getprev(base)
                    if base and getid(base) == glyph_code and getfont(base) == currentfont and getsubtype(base)<256 then
                        basechar = getchar(base)
                        if not marks[basechar] then
                            break
                        end
                    else
                        if trace_bugs then
                            logwarning("%s: no base for mark %s",pref(kind,lookupname),gref(markchar))
                        end
                        return head, start, false
                    end
                end
            end
            local index = getligaindex(start)
            local baseanchors = descriptions[basechar]
            if baseanchors then
                baseanchors = baseanchors.anchors
                if baseanchors then
                   local baseanchors = baseanchors['baselig']
                   if baseanchors then
                        local al = anchorlookups[lookupname]
                        for anchor, ba in next, baseanchors do
                            if al[anchor] then
                                local ma = markanchors[anchor]
                                if ma then
                                    ba = ba[index]
                                    if ba then
                                        local dx, dy, bound = setmark(start,base,tfmdata.parameters.factor,rlmode,ba,ma,characters[basechar]) -- index
                                        if trace_marks then
                                            logprocess("%s, anchor %s, index %s, bound %s: anchoring mark %s to baselig %s at index %s => (%p,%p)",
                                                pref(kind,lookupname),anchor,index,bound,gref(markchar),gref(basechar),index,dx,dy)
                                        end
                                        return head, start, true
                                    else
                                        if trace_bugs then
                                            logwarning("%s: no matching anchors for mark %s and baselig %s with index %a",pref(kind,lookupname),gref(markchar),gref(basechar),index)
                                        end
                                    end
                                end
                            end
                        end
                        if trace_bugs then
                            logwarning("%s: no matching anchors for mark %s and baselig %s",pref(kind,lookupname),gref(markchar),gref(basechar))
                        end
                    end
                end
            elseif trace_bugs then
            --  logwarning("%s: char %s is missing in font",pref(kind,lookupname),gref(basechar))
                onetimemessage(currentfont,basechar,"no base anchors",report_fonts)
            end
        elseif trace_bugs then
            logwarning("%s: prev node is no char",pref(kind,lookupname))
        end
    elseif trace_bugs then
        logwarning("%s: mark %s is no mark",pref(kind,lookupname),gref(markchar))
    end
    return head, start, false
end

function handlers.gpos_mark2mark(head,start,kind,lookupname,markanchors,sequence)
    local markchar = getchar(start)
    if marks[markchar] then
        local base = getprev(start) -- [glyph] [basemark] [start=mark]
        local slc = getligaindex(start)
        if slc then -- a rather messy loop ... needs checking with husayni
            while base do
                local blc = getligaindex(base)
                if blc and blc ~= slc then
                    base = getprev(base)
                else
                    break
                end
            end
        end
        if base and getid(base) == glyph_code and getfont(base) == currentfont and getsubtype(base)<256 then -- subtype test can go
            local basechar = getchar(base)
            local baseanchors = descriptions[basechar]
            if baseanchors then
                baseanchors = baseanchors.anchors
                if baseanchors then
                    baseanchors = baseanchors['basemark']
                    if baseanchors then
                        local al = anchorlookups[lookupname]
                        for anchor,ba in next, baseanchors do
                            if al[anchor] then
                                local ma = markanchors[anchor]
                                if ma then
                                    local dx, dy, bound = setmark(start,base,tfmdata.parameters.factor,rlmode,ba,ma,characters[basechar])
                                    if trace_marks then
                                        logprocess("%s, anchor %s, bound %s: anchoring mark %s to basemark %s => (%p,%p)",
                                            pref(kind,lookupname),anchor,bound,gref(markchar),gref(basechar),dx,dy)
                                    end
                                    return head, start, true
                                end
                            end
                        end
                        if trace_bugs then
                            logwarning("%s: no matching anchors for mark %s and basemark %s",pref(kind,lookupname),gref(markchar),gref(basechar))
                        end
                    end
                end
            elseif trace_bugs then
            --  logwarning("%s: char %s is missing in font",pref(kind,lookupname),gref(basechar))
                onetimemessage(currentfont,basechar,"no base anchors",report_fonts)
            end
        elseif trace_bugs then
            logwarning("%s: prev node is no mark",pref(kind,lookupname))
        end
    elseif trace_bugs then
        logwarning("%s: mark %s is no mark",pref(kind,lookupname),gref(markchar))
    end
    return head, start, false
end

function handlers.gpos_cursive(head,start,kind,lookupname,exitanchors,sequence) -- to be checked
    local alreadydone = cursonce and getprop(start,a_cursbase)
    if not alreadydone then
        local done = false
        local startchar = getchar(start)
        if marks[startchar] then
            if trace_cursive then
                logprocess("%s: ignoring cursive for mark %s",pref(kind,lookupname),gref(startchar))
            end
        else
            local nxt = getnext(start)
            while not done and nxt and getid(nxt) == glyph_code and getfont(nxt) == currentfont and getsubtype(nxt)<256 do
                local nextchar = getchar(nxt)
                if marks[nextchar] then
                    -- should not happen (maybe warning)
                    nxt = getnext(nxt)
                else
                    local entryanchors = descriptions[nextchar]
                    if entryanchors then
                        entryanchors = entryanchors.anchors
                        if entryanchors then
                            entryanchors = entryanchors['centry']
                            if entryanchors then
                                local al = anchorlookups[lookupname]
                                for anchor, entry in next, entryanchors do
                                    if al[anchor] then
                                        local exit = exitanchors[anchor]
                                        if exit then
                                            local dx, dy, bound = setcursive(start,nxt,tfmdata.parameters.factor,rlmode,exit,entry,characters[startchar],characters[nextchar])
                                            if trace_cursive then
                                                logprocess("%s: moving %s to %s cursive (%p,%p) using anchor %s and bound %s in rlmode %s",pref(kind,lookupname),gref(startchar),gref(nextchar),dx,dy,anchor,bound,rlmode)
                                            end
                                            done = true
                                            break
                                        end
                                    end
                                end
                            end
                        end
                    elseif trace_bugs then
                    --  logwarning("%s: char %s is missing in font",pref(kind,lookupname),gref(startchar))
                        onetimemessage(currentfont,startchar,"no entry anchors",report_fonts)
                    end
                    break
                end
            end
        end
        return head, start, done
    else
        if trace_cursive and trace_details then
            logprocess("%s, cursive %s is already done",pref(kind,lookupname),gref(getchar(start)),alreadydone)
        end
        return head, start, false
    end
end

function handlers.gpos_single(head,start,kind,lookupname,kerns,sequence,injection)
    local startchar = getchar(start)
    local dx, dy, w, h = setpair(start,tfmdata.parameters.factor,rlmode,sequence.flags[4],kerns,injection) -- ,characters[startchar])
    if trace_kerns then
        logprocess("%s: shifting single %s by (%p,%p) and correction (%p,%p)",pref(kind,lookupname),gref(startchar),dx,dy,w,h)
    end
    return head, start, false
end

function handlers.gpos_pair(head,start,kind,lookupname,kerns,sequence,lookuphash,i,injection)
    -- todo: kerns in disc nodes: pre, post, replace -> loop over disc too
    -- todo: kerns in components of ligatures
    local snext = getnext(start)
    if not snext then
        return head, start, false
    else
        local prev, done = start, false
        local factor = tfmdata.parameters.factor
        local lookuptype = lookuptypes[lookupname]
        while snext and getid(snext) == glyph_code and getfont(snext) == currentfont and getsubtype(snext)<256 do
            local nextchar = getchar(snext)
            local krn = kerns[nextchar]
            if not krn and marks[nextchar] then
                prev = snext
                snext = getnext(snext)
            else
                if not krn then
                    -- skip
                elseif type(krn) == "table" then
                    if lookuptype == "pair" then -- probably not needed
                        local a, b = krn[2], krn[3]
                        if a and #a > 0 then
                            local startchar = getchar(start)
                            local x, y, w, h = setpair(start,factor,rlmode,sequence.flags[4],a,injection) -- characters[startchar])
                            if trace_kerns then
                                logprocess("%s: shifting first of pair %s and %s by (%p,%p) and correction (%p,%p)",pref(kind,lookupname),gref(startchar),gref(nextchar),x,y,w,h)
                            end
                        end
                        if b and #b > 0 then
                            local startchar = getchar(start)
                            local x, y, w, h = setpair(snext,factor,rlmode,sequence.flags[4],b,injection) -- characters[nextchar])
                            if trace_kerns then
                                logprocess("%s: shifting second of pair %s and %s by (%p,%p) and correction (%p,%p)",pref(kind,lookupname),gref(startchar),gref(nextchar),x,y,w,h)
                            end
                        end
                    else -- wrong ... position has different entries
                        report_process("%s: check this out (old kern stuff)",pref(kind,lookupname))
                     -- local a, b = krn[2], krn[6]
                     -- if a and a ~= 0 then
                     --     local k = setkern(snext,factor,rlmode,a)
                     --     if trace_kerns then
                     --         logprocess("%s: inserting first kern %s between %s and %s",pref(kind,lookupname),k,gref(getchar(prev)),gref(nextchar))
                     --     end
                     -- end
                     -- if b and b ~= 0 then
                     --     logwarning("%s: ignoring second kern xoff %s",pref(kind,lookupname),b*factor)
                     -- end
                    end
                    done = true
                elseif krn ~= 0 then
                    local k = setkern(snext,factor,rlmode,krn,injection)
                    if trace_kerns then
                        logprocess("%s: inserting kern %s between %s and %s",pref(kind,lookupname),k,gref(getchar(prev)),gref(nextchar))
                    end
                    done = true
                end
                break
            end
        end
        return head, start, done
    end
end

--[[ldx--
<p>I will implement multiple chain replacements once I run into a font that uses
it. It's not that complex to handle.</p>
--ldx]]--

local chainmores = { }
local chainprocs = { }

local function logprocess(...)
    if trace_steps then
        registermessage(...)
    end
    report_subchain(...)
end

local logwarning = report_subchain

local function logprocess(...)
    if trace_steps then
        registermessage(...)
    end
    report_chain(...)
end

local logwarning = report_chain

-- We could share functions but that would lead to extra function calls with many
-- arguments, redundant tests and confusing messages.

function chainprocs.chainsub(head,start,stop,kind,chainname,currentcontext,lookuphash,lookuplist,chainlookupname)
    logwarning("%s: a direct call to chainsub cannot happen",cref(kind,chainname,chainlookupname))
    return head, start, false
end

function chainmores.chainsub(head,start,stop,kind,chainname,currentcontext,lookuphash,lookuplist,chainlookupname,n)
    logprocess("%s: a direct call to chainsub cannot happen",cref(kind,chainname,chainlookupname))
    return head, start, false
end

-- The reversesub is a special case, which is why we need to store the replacements
-- in a bit weird way. There is no lookup and the replacement comes from the lookup
-- itself. It is meant mostly for dealing with Urdu.

function chainprocs.reversesub(head,start,stop,kind,chainname,currentcontext,lookuphash,replacements)
    local char = getchar(start)
    local replacement = replacements[char]
    if replacement then
        if trace_singles then
            logprocess("%s: single reverse replacement of %s by %s",cref(kind,chainname),gref(char),gref(replacement))
        end
        resetinjection(start)
        setfield(start,"char",replacement)
        return head, start, true
    else
        return head, start, false
    end
end

--[[ldx--
<p>This chain stuff is somewhat tricky since we can have a sequence of actions to be
applied: single, alternate, multiple or ligature where ligature can be an invalid
one in the sense that it will replace multiple by one but not neccessary one that
looks like the combination (i.e. it is the counterpart of multiple then). For
example, the following is valid:</p>

<typing>
<line>xxxabcdexxx [single a->A][multiple b->BCD][ligature cde->E] xxxABCDExxx</line>
</typing>

<p>Therefore we we don't really do the replacement here already unless we have the
single lookup case. The efficiency of the replacements can be improved by deleting
as less as needed but that would also make the code even more messy.</p>
--ldx]]--

-- local function delete_till_stop(head,start,stop,ignoremarks) -- keeps start
--     local n = 1
--     if start == stop then
--         -- done
--     elseif ignoremarks then
--         repeat -- start x x m x x stop => start m
--             local next = getnext(start)
--             if not marks[getchar(next)] then
--                 local components = getfield(next,"components")
--                 if components then -- probably not needed
--                     flush_node_list(components)
--                 end
--                 head = delete_node(head,next)
--             end
--             n = n + 1
--         until next == stop
--     else -- start x x x stop => start
--         repeat
--             local next = getnext(start)
--             local components = getfield(next,"components")
--             if components then -- probably not needed
--                 flush_node_list(components)
--             end
--             head = delete_node(head,next)
--             n = n + 1
--         until next == stop
--     end
--     return head, n
-- end

--[[ldx--
<p>Here we replace start by a single variant.</p>
--ldx]]--

function chainprocs.gsub_single(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname,chainindex)
    -- todo: marks ?
    local current = start
    local subtables = currentlookup.subtables
    if #subtables > 1 then
        logwarning("todo: check if we need to loop over the replacements: % t",subtables)
    end
    while current do
        if getid(current) == glyph_code then
            local currentchar = getchar(current)
            local lookupname = subtables[1] -- only 1
            local replacement = lookuphash[lookupname]
            if not replacement then
                if trace_bugs then
                    logwarning("%s: no single hits",cref(kind,chainname,chainlookupname,lookupname,chainindex))
                end
            else
                replacement = replacement[currentchar]
                if not replacement or replacement == "" then
                    if trace_bugs then
                        logwarning("%s: no single for %s",cref(kind,chainname,chainlookupname,lookupname,chainindex),gref(currentchar))
                    end
                else
                    if trace_singles then
                        logprocess("%s: replacing single %s by %s",cref(kind,chainname,chainlookupname,lookupname,chainindex),gref(currentchar),gref(replacement))
                    end
                    resetinjection(current)
                    if check_discretionaries then
                        -- some fonts use a chain lookup to replace e.g. an f in a fi ligature
                        -- and there can be a disc node in between ... the next code tries to catch
                        -- this
                        local next = getnext(current)
                        local prev = getprev(current) -- todo: just remember it above
                        local done = false
                        if next then
                            if getid(next) == disc_code then
                                local subtype = getsubtype(next)
                                if subtype == discretionary_code then
                                    setfield(next,"prev",prev)
                                    setfield(prev,"next",next)
                                    setfield(current,"prev",nil)
                                    setfield(current,"next",nil)
                                    local replace = getfield(next,"replace")
                                    local pre     = getfield(next,"pre")
                                    local new     = copy_node(current)
                                    setfield(new,"char",replacement)
                                    if replace then
                                        setfield(new,"next",replace)
                                        setfield(replace,"prev",new)
                                    end
                                    if pre then
                                        setfield(current,"next",pre)
                                        setfield(pre,"prev",current)
                                    end
                                    setfield(next,"replace",new) -- also updates tail
                                    setfield(next,"pre",current) -- also updates tail
                                end
                                start = next
                                done = true
                                local next = getnext(start)
                                if next and getid(next) == disc_code then
                                    collapse_disc(start,next)
                                end
                            end
                        end
                        if not done and prev then
                            if getid(prev) == disc_code then
                                local subtype = getsubtype(prev)
                                if subtype == discretionary_code then
                                    setfield(next,"prev",prev)
                                    setfield(prev,"next",next)
                                    setfield(current,"prev",nil)
                                    setfield(current,"next",nil)
                                    local replace = getfield(prev,"replace")
                                    local post    = getfield(prev,"post")
                                    local new     = copy_node(current)
                                    setfield(new,"char",replacement)
                                    if replace then
                                        local tail = find_node_tail(replace)
                                        setfield(tail,"next",new)
                                        setfield(new,"prev",tail)
                                    else
                                        replace = new
                                    end
                                    if post then
                                        local tail = find_node_tail(post)
                                        setfield(tail,"next",current)
                                        setfield(current,"prev",tail)
                                    else
                                        post = current
                                    end
                                    setfield(prev,"replace",replace) -- also updates tail
                                    setfield(prev,"post",post)       -- also updates tail
                                    start = prev
                                    done = true
                                end
                            end
                        end
                        if not done then
                            setfield(current,"char",replacement)
                        end
                    else
                        setfield(current,"char",replacement)
                    end
                end
            end
            return head, start, true
        elseif current == stop then
            break
        else
            current = getnext(current)
        end
    end
    return head, start, false
end

chainmores.gsub_single = chainprocs.gsub_single

--[[ldx--
<p>Here we replace start by a sequence of new glyphs.</p>
--ldx]]--

function chainprocs.gsub_multiple(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname)
 -- local head, n = delete_till_stop(head,start,stop)
    local startchar = getchar(start)
    local subtables = currentlookup.subtables
    local lookupname = subtables[1]
    local replacements = lookuphash[lookupname]
    if not replacements then
        if trace_bugs then
            logwarning("%s: no multiple hits",cref(kind,chainname,chainlookupname,lookupname))
        end
    else
        replacements = replacements[startchar]
        if not replacements or replacement == "" then
            if trace_bugs then
                logwarning("%s: no multiple for %s",cref(kind,chainname,chainlookupname,lookupname),gref(startchar))
            end
        else
            if trace_multiples then
                logprocess("%s: replacing %s by multiple characters %s",cref(kind,chainname,chainlookupname,lookupname),gref(startchar),gref(replacements))
            end
            return multiple_glyphs(head,start,replacements,currentlookup.flags[1])
        end
    end
    return head, start, false
end

chainmores.gsub_multiple = chainprocs.gsub_multiple

--[[ldx--
<p>Here we replace start by new glyph. First we delete the rest of the match.</p>
--ldx]]--

-- char_1 mark_1 -> char_x mark_1 (ignore marks)
-- char_1 mark_1 -> char_x

-- to be checked: do we always have just one glyph?
-- we can also have alternates for marks
-- marks come last anyway
-- are there cases where we need to delete the mark

function chainprocs.gsub_alternate(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname)
    local current = start
    local subtables = currentlookup.subtables
    local value  = featurevalue == true and tfmdata.shared.features[kind] or featurevalue
    while current do
        if getid(current) == glyph_code then -- is this check needed?
            local currentchar = getchar(current)
            local lookupname = subtables[1]
            local alternatives = lookuphash[lookupname]
            if not alternatives then
                if trace_bugs then
                    logwarning("%s: no alternative hit",cref(kind,chainname,chainlookupname,lookupname))
                end
            else
                alternatives = alternatives[currentchar]
                if alternatives then
                    local choice, comment = get_alternative_glyph(current,alternatives,value,trace_alternatives)
                    if choice then
                        if trace_alternatives then
                            logprocess("%s: replacing %s by alternative %a to %s, %s",cref(kind,chainname,chainlookupname,lookupname),gref(char),choice,gref(choice),comment)
                        end
                        resetinjection(start)
                        setfield(start,"char",choice)
                    else
                        if trace_alternatives then
                            logwarning("%s: no variant %a for %s, %s",cref(kind,chainname,chainlookupname,lookupname),value,gref(char),comment)
                        end
                    end
                elseif trace_bugs then
                    logwarning("%s: no alternative for %s, %s",cref(kind,chainname,chainlookupname,lookupname),gref(currentchar),comment)
                end
            end
            return head, start, true
        elseif current == stop then
            break
        else
            current = getnext(current)
        end
    end
    return head, start, false
end

chainmores.gsub_alternate = chainprocs.gsub_alternate

--[[ldx--
<p>When we replace ligatures we use a helper that handles the marks. I might change
this function (move code inline and handle the marks by a separate function). We
assume rather stupid ligatures (no complex disc nodes).</p>
--ldx]]--

function chainprocs.gsub_ligature(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname,chainindex)
    local startchar = getchar(start)
    local subtables = currentlookup.subtables
    local lookupname = subtables[1]
    local ligatures = lookuphash[lookupname]
    if not ligatures then
        if trace_bugs then
            logwarning("%s: no ligature hits",cref(kind,chainname,chainlookupname,lookupname,chainindex))
        end
    else
        ligatures = ligatures[startchar]
        if not ligatures then
            if trace_bugs then
                logwarning("%s: no ligatures starting with %s",cref(kind,chainname,chainlookupname,lookupname,chainindex),gref(startchar))
            end
        else
            local s = getnext(start)
            local discfound = false
            local last = stop
            local nofreplacements = 0
            local skipmark = currentlookup.flags[1]
            while s do
                local id = getid(s)
                if id == disc_code then
                    if not discfound then
                        discfound = s
                    end
                    if s == stop then
                        break -- okay? or before the disc
                    else
                        s = getnext(s)
                    end
                else
                    local schar = getchar(s)
                    if skipmark and marks[schar] then -- marks
-- if s == stop then -- maybe add this
--     break
-- else
                        s = getnext(s)
-- end
                    else
                        local lg = ligatures[schar]
                        if lg then
                            ligatures, last, nofreplacements = lg, s, nofreplacements + 1
                            if s == stop then
                                break
                            else
                                s = getnext(s)
                            end
                        else
                            break
                        end
                    end
                end
            end
            local l2 = ligatures.ligature
            if l2 then
                if chainindex then
                    stop = last
                end
                if trace_ligatures then
                    if start == stop then
                        logprocess("%s: replacing character %s by ligature %s case 3",cref(kind,chainname,chainlookupname,lookupname,chainindex),gref(startchar),gref(l2))
                    else
                        logprocess("%s: replacing character %s upto %s by ligature %s case 4",cref(kind,chainname,chainlookupname,lookupname,chainindex),gref(startchar),gref(getchar(stop)),gref(l2))
                    end
                end
                head, start = toligature(kind,lookupname,head,start,stop,l2,currentlookup.flags[1],discfound)
                return head, start, true, nofreplacements, discfound
            elseif trace_bugs then
                if start == stop then
                    logwarning("%s: replacing character %s by ligature fails",cref(kind,chainname,chainlookupname,lookupname,chainindex),gref(startchar))
                else
                    logwarning("%s: replacing character %s upto %s by ligature fails",cref(kind,chainname,chainlookupname,lookupname,chainindex),gref(startchar),gref(getchar(stop)))
                end
            end
        end
    end
    return head, start, false, 0, false
end

chainmores.gsub_ligature = chainprocs.gsub_ligature

function chainprocs.gpos_mark2base(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname)
    local markchar = getchar(start)
    if marks[markchar] then
        local subtables = currentlookup.subtables
        local lookupname = subtables[1]
        local markanchors = lookuphash[lookupname]
        if markanchors then
            markanchors = markanchors[markchar]
        end
        if markanchors then
            local base = getprev(start) -- [glyph] [start=mark]
            if base and getid(base) == glyph_code and getfont(base) == currentfont and getsubtype(base)<256 then
                local basechar = getchar(base)
                if marks[basechar] then
                    while true do
                        base = getprev(base)
                        if base and getid(base) == glyph_code and getfont(base) == currentfont and getsubtype(base)<256 then
                            basechar = getchar(base)
                            if not marks[basechar] then
                                break
                            end
                        else
                            if trace_bugs then
                                logwarning("%s: no base for mark %s",pref(kind,lookupname),gref(markchar))
                            end
                            return head, start, false
                        end
                    end
                end
                local baseanchors = descriptions[basechar].anchors
                if baseanchors then
                    local baseanchors = baseanchors['basechar']
                    if baseanchors then
                        local al = anchorlookups[lookupname]
                        for anchor,ba in next, baseanchors do
                            if al[anchor] then
                                local ma = markanchors[anchor]
                                if ma then
                                    local dx, dy, bound = setmark(start,base,tfmdata.parameters.factor,rlmode,ba,ma,characters[basechar])
                                    if trace_marks then
                                        logprocess("%s, anchor %s, bound %s: anchoring mark %s to basechar %s => (%p,%p)",
                                            cref(kind,chainname,chainlookupname,lookupname),anchor,bound,gref(markchar),gref(basechar),dx,dy)
                                    end
                                    return head, start, true
                                end
                            end
                        end
                        if trace_bugs then
                            logwarning("%s, no matching anchors for mark %s and base %s",cref(kind,chainname,chainlookupname,lookupname),gref(markchar),gref(basechar))
                        end
                    end
                end
            elseif trace_bugs then
                logwarning("%s: prev node is no char",cref(kind,chainname,chainlookupname,lookupname))
            end
        elseif trace_bugs then
            logwarning("%s: mark %s has no anchors",cref(kind,chainname,chainlookupname,lookupname),gref(markchar))
        end
    elseif trace_bugs then
        logwarning("%s: mark %s is no mark",cref(kind,chainname,chainlookupname),gref(markchar))
    end
    return head, start, false
end

function chainprocs.gpos_mark2ligature(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname)
    local markchar = getchar(start)
    if marks[markchar] then
        local subtables = currentlookup.subtables
        local lookupname = subtables[1]
        local markanchors = lookuphash[lookupname]
        if markanchors then
            markanchors = markanchors[markchar]
        end
        if markanchors then
            local base = getprev(start) -- [glyph] [optional marks] [start=mark]
            if base and getid(base) == glyph_code and getfont(base) == currentfont and getsubtype(base)<256 then
                local basechar = getchar(base)
                if marks[basechar] then
                    while true do
                        base = getprev(base)
                        if base and getid(base) == glyph_code and getfont(base) == currentfont and getsubtype(base)<256 then
                            basechar = getchar(base)
                            if not marks[basechar] then
                                break
                            end
                        else
                            if trace_bugs then
                                logwarning("%s: no base for mark %s",cref(kind,chainname,chainlookupname,lookupname),markchar)
                            end
                            return head, start, false
                        end
                    end
                end
                -- todo: like marks a ligatures hash
                local index = getligaindex(start)
                local baseanchors = descriptions[basechar].anchors
                if baseanchors then
                   local baseanchors = baseanchors['baselig']
                   if baseanchors then
                        local al = anchorlookups[lookupname]
                        for anchor,ba in next, baseanchors do
                            if al[anchor] then
                                local ma = markanchors[anchor]
                                if ma then
                                    ba = ba[index]
                                    if ba then
                                        local dx, dy, bound = setmark(start,base,tfmdata.parameters.factor,rlmode,ba,ma,characters[basechar])
                                        if trace_marks then
                                            logprocess("%s, anchor %s, bound %s: anchoring mark %s to baselig %s at index %s => (%p,%p)",
                                                cref(kind,chainname,chainlookupname,lookupname),anchor,a or bound,gref(markchar),gref(basechar),index,dx,dy)
                                        end
                                        return head, start, true
                                    end
                                end
                            end
                        end
                        if trace_bugs then
                            logwarning("%s: no matching anchors for mark %s and baselig %s",cref(kind,chainname,chainlookupname,lookupname),gref(markchar),gref(basechar))
                        end
                    end
                end
            elseif trace_bugs then
                logwarning("feature %s, lookup %s: prev node is no char",kind,lookupname)
            end
        elseif trace_bugs then
            logwarning("%s: mark %s has no anchors",cref(kind,chainname,chainlookupname,lookupname),gref(markchar))
        end
    elseif trace_bugs then
        logwarning("%s: mark %s is no mark",cref(kind,chainname,chainlookupname),gref(markchar))
    end
    return head, start, false
end

function chainprocs.gpos_mark2mark(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname)
    local markchar = getchar(start)
    if marks[markchar] then
    --  local markanchors = descriptions[markchar].anchors markanchors = markanchors and markanchors.mark
        local subtables = currentlookup.subtables
        local lookupname = subtables[1]
        local markanchors = lookuphash[lookupname]
        if markanchors then
            markanchors = markanchors[markchar]
        end
        if markanchors then
            local base = getprev(start) -- [glyph] [basemark] [start=mark]
            local slc = getligaindex(start)
            if slc then -- a rather messy loop ... needs checking with husayni
                while base do
                    local blc = getligaindex(base)
                    if blc and blc ~= slc then
                        base = getprev(base)
                    else
                        break
                    end
                end
            end
            if base and getid(base) == glyph_code and getfont(base) == currentfont and getsubtype(base)<256 then -- subtype test can go
                local basechar = getchar(base)
                local baseanchors = descriptions[basechar].anchors
                if baseanchors then
                    baseanchors = baseanchors['basemark']
                    if baseanchors then
                        local al = anchorlookups[lookupname]
                        for anchor,ba in next, baseanchors do
                            if al[anchor] then
                                local ma = markanchors[anchor]
                                if ma then
                                    local dx, dy, bound = setmark(start,base,tfmdata.parameters.factor,rlmode,ba,ma,characters[basechar])
                                    if trace_marks then
                                        logprocess("%s, anchor %s, bound %s: anchoring mark %s to basemark %s => (%p,%p)",
                                            cref(kind,chainname,chainlookupname,lookupname),anchor,bound,gref(markchar),gref(basechar),dx,dy)
                                    end
                                    return head, start, true
                                end
                            end
                        end
                        if trace_bugs then
                            logwarning("%s: no matching anchors for mark %s and basemark %s",gref(kind,chainname,chainlookupname,lookupname),gref(markchar),gref(basechar))
                        end
                    end
                end
            elseif trace_bugs then
                logwarning("%s: prev node is no mark",cref(kind,chainname,chainlookupname,lookupname))
            end
        elseif trace_bugs then
            logwarning("%s: mark %s has no anchors",cref(kind,chainname,chainlookupname,lookupname),gref(markchar))
        end
    elseif trace_bugs then
        logwarning("%s: mark %s is no mark",cref(kind,chainname,chainlookupname),gref(markchar))
    end
    return head, start, false
end

function chainprocs.gpos_cursive(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname)
    local alreadydone = cursonce and getprop(start,a_cursbase)
    if not alreadydone then
        local startchar = getchar(start)
        local subtables = currentlookup.subtables
        local lookupname = subtables[1]
        local exitanchors = lookuphash[lookupname]
        if exitanchors then
            exitanchors = exitanchors[startchar]
        end
        if exitanchors then
            local done = false
            if marks[startchar] then
                if trace_cursive then
                    logprocess("%s: ignoring cursive for mark %s",pref(kind,lookupname),gref(startchar))
                end
            else
                local nxt = getnext(start)
                while not done and nxt and getid(nxt) == glyph_code and getfont(nxt) == currentfont and getsubtype(nxt)<256 do
                    local nextchar = getchar(nxt)
                    if marks[nextchar] then
                        -- should not happen (maybe warning)
                        nxt = getnext(nxt)
                    else
                        local entryanchors = descriptions[nextchar]
                        if entryanchors then
                            entryanchors = entryanchors.anchors
                            if entryanchors then
                                entryanchors = entryanchors['centry']
                                if entryanchors then
                                    local al = anchorlookups[lookupname]
                                    for anchor, entry in next, entryanchors do
                                        if al[anchor] then
                                            local exit = exitanchors[anchor]
                                            if exit then
                                                local dx, dy, bound = setcursive(start,nxt,tfmdata.parameters.factor,rlmode,exit,entry,characters[startchar],characters[nextchar])
                                                if trace_cursive then
                                                    logprocess("%s: moving %s to %s cursive (%p,%p) using anchor %s and bound %s in rlmode %s",pref(kind,lookupname),gref(startchar),gref(nextchar),dx,dy,anchor,bound,rlmode)
                                                end
                                                done = true
                                                break
                                            end
                                        end
                                    end
                                end
                            end
                        elseif trace_bugs then
                        --  logwarning("%s: char %s is missing in font",pref(kind,lookupname),gref(startchar))
                            onetimemessage(currentfont,startchar,"no entry anchors",report_fonts)
                        end
                        break
                    end
                end
            end
            return head, start, done
        else
            if trace_cursive and trace_details then
                logprocess("%s, cursive %s is already done",pref(kind,lookupname),gref(getchar(start)),alreadydone)
            end
            return head, start, false
        end
    end
    return head, start, false
end

function chainprocs.gpos_single(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname,chainindex,sequence)
    -- untested .. needs checking for the new model
    local startchar = getchar(start)
    local subtables = currentlookup.subtables
    local lookupname = subtables[1]
    local kerns = lookuphash[lookupname]
    if kerns then
        kerns = kerns[startchar] -- needed ?
        if kerns then
            local dx, dy, w, h = setpair(start,tfmdata.parameters.factor,rlmode,sequence.flags[4],kerns) -- ,characters[startchar])
            if trace_kerns then
                logprocess("%s: shifting single %s by (%p,%p) and correction (%p,%p)",cref(kind,chainname,chainlookupname),gref(startchar),dx,dy,w,h)
            end
        end
    end
    return head, start, false
end

chainmores.gpos_single = chainprocs.gpos_single -- okay?

-- when machines become faster i will make a shared function

function chainprocs.gpos_pair(head,start,stop,kind,chainname,currentcontext,lookuphash,currentlookup,chainlookupname,chainindex,sequence)
    local snext = getnext(start)
    if snext then
        local startchar = getchar(start)
        local subtables = currentlookup.subtables
        local lookupname = subtables[1]
        local kerns = lookuphash[lookupname]
        if kerns then
            kerns = kerns[startchar]
            if kerns then
                local lookuptype = lookuptypes[lookupname]
                local prev, done = start, false
                local factor = tfmdata.parameters.factor
                while snext and getid(snext) == glyph_code and getfont(snext) == currentfont and getsubtype(snext)<256 do
                    local nextchar = getchar(snext)
                    local krn = kerns[nextchar]
                    if not krn and marks[nextchar] then
                        prev = snext
                        snext = getnext(snext)
                    else
                        if not krn then
                            -- skip
                        elseif type(krn) == "table" then
                            if lookuptype == "pair" then
                                local a, b = krn[2], krn[3]
                                if a and #a > 0 then
                                    local startchar = getchar(start)
                                    local x, y, w, h = setpair(start,factor,rlmode,sequence.flags[4],a) -- ,characters[startchar])
                                    if trace_kerns then
                                        logprocess("%s: shifting first of pair %s and %s by (%p,%p) and correction (%p,%p)",cref(kind,chainname,chainlookupname),gref(startchar),gref(nextchar),x,y,w,h)
                                    end
                                end
                                if b and #b > 0 then
                                    local startchar = getchar(start)
                                    local x, y, w, h = setpair(snext,factor,rlmode,sequence.flags[4],b) -- ,characters[nextchar])
                                    if trace_kerns then
                                        logprocess("%s: shifting second of pair %s and %s by (%p,%p) and correction (%p,%p)",cref(kind,chainname,chainlookupname),gref(startchar),gref(nextchar),x,y,w,h)
                                    end
                                end
                            else
                                report_process("%s: check this out (old kern stuff)",cref(kind,chainname,chainlookupname))
                                local a, b = krn[2], krn[6]
                                if a and a ~= 0 then
                                    local k = setkern(snext,factor,rlmode,a)
                                    if trace_kerns then
                                        logprocess("%s: inserting first kern %s between %s and %s",cref(kind,chainname,chainlookupname),k,gref(getchar(prev)),gref(nextchar))
                                    end
                                end
                                if b and b ~= 0 then
                                    logwarning("%s: ignoring second kern xoff %s",cref(kind,chainname,chainlookupname),b*factor)
                                end
                            end
                            done = true
                        elseif krn ~= 0 then
                            local k = setkern(snext,factor,rlmode,krn)
                            if trace_kerns then
                                logprocess("%s: inserting kern %s between %s and %s",cref(kind,chainname,chainlookupname),k,gref(getchar(prev)),gref(nextchar))
                            end
                            done = true
                        end
                        break
                    end
                end
                return head, start, done
            end
        end
    end
    return head, start, false
end

chainmores.gpos_pair = chainprocs.gpos_pair -- okay?

-- what pointer to return, spec says stop
-- to be discussed ... is bidi changer a space?
-- elseif char == zwnj and sequence[n][32] then -- brrr

-- somehow l or f is global
-- we don't need to pass the currentcontext, saves a bit
-- make a slow variant then can be activated but with more tracing

local function show_skip(kind,chainname,char,ck,class)
    if ck[9] then
        logwarning("%s: skipping char %s, class %a, rule %a, lookuptype %a, %a => %a",cref(kind,chainname),gref(char),class,ck[1],ck[2],ck[9],ck[10])
    else
        logwarning("%s: skipping char %s, class %a, rule %a, lookuptype %a",cref(kind,chainname),gref(char),class,ck[1],ck[2])
    end
end

local function normal_handle_contextchain(head,start,kind,chainname,contexts,sequence,lookuphash)
    --  local rule, lookuptype, sequence, f, l, lookups = ck[1], ck[2] ,ck[3], ck[4], ck[5], ck[6]
    local flags        = sequence.flags
    local done         = false
    local skipmark     = flags[1]
    local skipligature = flags[2]
    local skipbase     = flags[3]
    local someskip     = skipmark or skipligature or skipbase -- could be stored in flags for a fast test (hm, flags could be false !)
    local markclass    = sequence.markclass                   -- todo, first we need a proper test
    local skipped      = false
    for k=1,#contexts do
        local match   = true
        local current = start
        local last    = start
        local ck      = contexts[k]
        local seq     = ck[3]
        local s       = #seq
        -- f..l = mid string
        if s == 1 then
            -- never happens
            match = getid(current) == glyph_code and getfont(current) == currentfont and getsubtype(current)<256 and seq[1][getchar(current)]
        else
            -- maybe we need a better space check (maybe check for glue or category or combination)
            -- we cannot optimize for n=2 because there can be disc nodes
            local f, l = ck[4], ck[5]
            -- current match
            if f == 1 and f == l then -- current only
                -- already a hit
             -- match = true
            else -- before/current/after | before/current | current/after
                -- no need to test first hit (to be optimized)
                if f == l then -- new, else last out of sync (f is > 1)
                 -- match = true
                else
                    local n = f + 1
                    last = getnext(last)
                    while n <= l do
                        if last then
                            local id = getid(last)
                            if id == glyph_code then
                                if getfont(last) == currentfont and getsubtype(last)<256 then
                                    local char = getchar(last)
                                    local ccd = descriptions[char]
                                    if ccd then
                                        local class = ccd.class
                                        if class == skipmark or class == skipligature or class == skipbase or (markclass and class == "mark" and not markclass[char]) then
                                            skipped = true
                                            if trace_skips then
                                                show_skip(kind,chainname,char,ck,class)
                                            end
                                            last = getnext(last)
                                        elseif seq[n][char] then
                                            if n < l then
                                                last = getnext(last)
                                            end
                                            n = n + 1
                                        else
                                            match = false
                                            break
                                        end
                                    else
                                        match = false
                                        break
                                    end
                                else
                                    match = false
                                    break
                                end
                            elseif id == disc_code then
                                if check_discretionaries then
                                    local replace = getfield(last,"replace")
                                    if replace then
                                        -- so far we never entered this branch
                                        while replace do
                                            if seq[n][getchar(replace)] then
                                                n = n + 1
                                                replace = getnext(replace)
                                                if not replace then
                                                    break
                                                elseif n > l then
                                                 -- match = false
                                                    break
                                                end
                                            else
                                                match = false
                                                break
                                            end
                                        end
                                        if not match then
                                            break
                                        elseif check_discretionaries == "trace" then
                                            report_chain("check disc action in current")
                                        end
                                    else
                                        last = getnext(last) -- no skipping here
                                    end
                                else
                                    last = getnext(last) -- no skipping here
                                end
                            else
                                match = false
                                break
                            end
                        else
                            match = false
                            break
                        end
                    end
                end
            end
            -- before
            if match and f > 1 then
                local prev = getprev(start)
                if prev then
                    local n = f-1
                    while n >= 1 do
                        if prev then
                            local id = getid(prev)
                            if id == glyph_code then
                                if getfont(prev) == currentfont and getsubtype(prev)<256 then -- normal char
                                    local char = getchar(prev)
                                    local ccd = descriptions[char]
                                    if ccd then
                                        local class = ccd.class
                                        if class == skipmark or class == skipligature or class == skipbase or (markclass and class == "mark" and not markclass[char]) then
                                            skipped = true
                                            if trace_skips then
                                                show_skip(kind,chainname,char,ck,class)
                                            end
                                        elseif seq[n][char] then
                                            n = n -1
                                        else
                                            match = false
                                            break
                                        end
                                    else
                                        match = false
                                        break
                                    end
                                else
                                    match = false
                                    break
                                end
                            elseif id == disc_code then
                                -- the special case: f i where i becomes dottless i ..
                                if check_discretionaries then
                                    local replace = getfield(prev,"replace")
                                    if replace then
                                        -- we seldom enter this branch (e.g. on brill efficient)
                                        replace = find_node_tail(replace)
                                        local finish = getprev(replace)
                                        while replace do
                                            if seq[n][getchar(replace)] then
                                                n = n - 1
                                                replace = getprev(replace)
                                                if not replace or replace == finish then
                                                    break
                                                elseif n < 1 then
                                                 -- match = false
                                                    break
                                                end
                                            else
                                                match = false
                                                break
                                            end
                                        end
                                        if not match then
                                            break
                                        elseif check_discretionaries == "trace" then
                                            report_chain("check disc action in before")
                                        end
                                    else
                                        -- skip 'm
                                    end
                                else
                                    -- skip 'm
                                end
                            elseif seq[n][32] then
                                n = n -1
                            else
                                match = false
                                break
                            end
                            prev = getprev(prev)
                        elseif seq[n][32] then -- somewhat special, as zapfino can have many preceding spaces
                            n = n - 1
                        else
                            match = false
                            break
                        end
                    end
                else
                    match = false
                end
            end
            -- after
            if match and s > l then
                local current = last and getnext(last)
                if current then
                    -- removed optimization for s-l == 1, we have to deal with marks anyway
                    local n = l + 1
                    while n <= s do
                        if current then
                            local id = getid(current)
                            if id == glyph_code then
                                if getfont(current) == currentfont and getsubtype(current)<256 then -- normal char
                                    local char = getchar(current)
                                    local ccd = descriptions[char]
                                    if ccd then
                                        local class = ccd.class
                                        if class == skipmark or class == skipligature or class == skipbase or (markclass and class == "mark" and not markclass[char]) then
                                            skipped = true
                                            if trace_skips then
                                                show_skip(kind,chainname,char,ck,class)
                                            end
                                        elseif seq[n][char] then
                                            n = n + 1
                                        else
                                            match = false
                                            break
                                        end
                                    else
                                        match = false
                                        break
                                    end
                                else
                                    match = false
                                    break
                                end
                            elseif id == disc_code then
                                if check_discretionaries then
                                    local replace = getfield(current,"replace")
                                    if replace then
                                        -- so far we never entered this branch
                                        while replace do
                                            if seq[n][getchar(replace)] then
                                                n = n + 1
                                                replace = getnext(replace)
                                                if not replace then
                                                    break
                                                elseif n > s then
                                                    break
                                                end
                                            else
                                                match = false
                                                break
                                            end
                                        end
                                        if not match then
                                            break
                                        elseif check_discretionaries == "trace" then
                                            report_chain("check disc action in after")
                                        end
                                    else
                                        -- skip 'm
                                    end
                                else
                                    -- skip 'm
                                end
                            elseif seq[n][32] then -- brrr
                                n = n + 1
                            else
                                match = false
                                break
                            end
                            current = getnext(current)
                        elseif seq[n][32] then
                            n = n + 1
                        else
                            match = false
                            break
                        end
                    end
                else
                    match = false
                end
            end
        end
        if match then
            -- ck == currentcontext
            if trace_contexts then
                local rule, lookuptype, f, l = ck[1], ck[2], ck[4], ck[5]
                local char = getchar(start)
                if ck[9] then
                    logwarning("%s: rule %s matches at char %s for (%s,%s,%s) chars, lookuptype %a, %a => %a",
                        cref(kind,chainname),rule,gref(char),f-1,l-f+1,s-l,lookuptype,ck[9],ck[10])
                else
                    logwarning("%s: rule %s matches at char %s for (%s,%s,%s) chars, lookuptype %a",
                        cref(kind,chainname),rule,gref(char),f-1,l-f+1,s-l,lookuptype)
                end
            end
            local chainlookups = ck[6]
            if chainlookups then
                local nofchainlookups = #chainlookups
                -- we can speed this up if needed
                if nofchainlookups == 1 then
                    local chainlookupname = chainlookups[1]
                    local chainlookup = lookuptable[chainlookupname]
                    if chainlookup then
                        local cp = chainprocs[chainlookup.type]
                        if cp then
                            local ok
                            head, start, ok = cp(head,start,last,kind,chainname,ck,lookuphash,chainlookup,chainlookupname,nil,sequence)
                            if ok then
                                done = true
                            end
                        else
                            logprocess("%s: %s is not yet supported",cref(kind,chainname,chainlookupname),chainlookup.type)
                        end
                    else -- shouldn't happen
                        logprocess("%s is not yet supported",cref(kind,chainname,chainlookupname))
                    end
                 else
                    local i = 1
                    while true do
                        if skipped then
                            while true do
                                local char = getchar(start)
                                local ccd = descriptions[char]
                                if ccd then
                                    local class = ccd.class
                                    if class == skipmark or class == skipligature or class == skipbase or (markclass and class == "mark" and not markclass[char]) then
                                        start = getnext(start)
                                    else
                                        break
                                    end
                                else
                                    break
                                end
                            end
                        end
                        local chainlookupname = chainlookups[i]
                        local chainlookup = lookuptable[chainlookupname]
                        if not chainlookup then
                            -- okay, n matches, < n replacements
                            i = i + 1
                        else
                            local cp = chainmores[chainlookup.type]
                            if not cp then
                                -- actually an error
                                logprocess("%s: %s is not yet supported",cref(kind,chainname,chainlookupname),chainlookup.type)
                                i = i + 1
                            else
                                local ok, n
                                head, start, ok, n = cp(head,start,last,kind,chainname,ck,lookuphash,chainlookup,chainlookupname,i,sequence)
                                -- messy since last can be changed !
                                if ok then
                                    done = true
                                    -- skip next one(s) if ligature
                                    i = i + (n or 1)
                                else
                                    i = i + 1
                                end
                            end
                        end
                        if i > nofchainlookups then
                            break
                        elseif start then
                            start = getnext(start)
                        else
                            -- weird
                        end
                    end
                end
            else
                local replacements = ck[7]
                if replacements then
                    head, start, done = chainprocs.reversesub(head,start,last,kind,chainname,ck,lookuphash,replacements) -- sequence
                else
                    done = quit_on_no_replacement -- can be meant to be skipped / quite inconsistent in fonts
                    if trace_contexts then
                        logprocess("%s: skipping match",cref(kind,chainname))
                    end
                end
            end
        end
    end
    return head, start, done
end

-- Because we want to keep this elsewhere (an because speed is less an issue) we
-- pass the font id so that the verbose variant can access the relevant helper tables.

local verbose_handle_contextchain = function(font,...)
    logwarning("no verbose handler installed, reverting to 'normal'")
    otf.setcontextchain()
    return normal_handle_contextchain(...)
end

otf.chainhandlers = {
    normal  = normal_handle_contextchain,
    verbose = verbose_handle_contextchain,
}

function otf.setcontextchain(method)
    if not method or method == "normal" or not otf.chainhandlers[method] then
        if handlers.contextchain then -- no need for a message while making the format
            logwarning("installing normal contextchain handler")
        end
        handlers.contextchain = normal_handle_contextchain
    else
        logwarning("installing contextchain handler %a",method)
        local handler = otf.chainhandlers[method]
        handlers.contextchain = function(...)
            return handler(currentfont,...) -- hm, get rid of ...
        end
    end
    handlers.gsub_context             = handlers.contextchain
    handlers.gsub_contextchain        = handlers.contextchain
    handlers.gsub_reversecontextchain = handlers.contextchain
    handlers.gpos_contextchain        = handlers.contextchain
    handlers.gpos_context             = handlers.contextchain
end

otf.setcontextchain()

local missing = { } -- we only report once

local function logprocess(...)
    if trace_steps then
        registermessage(...)
    end
    report_process(...)
end

local logwarning = report_process

local function report_missing_cache(typ,lookup)
    local f = missing[currentfont] if not f then f = { } missing[currentfont] = f end
    local t = f[typ]               if not t then t = { } f[typ]               = t end
    if not t[lookup] then
        t[lookup] = true
        logwarning("missing cache for lookup %a, type %a, font %a, name %a",lookup,typ,currentfont,tfmdata.properties.fullname)
    end
end

local resolved = { } -- we only resolve a font,script,language pair once

-- todo: pass all these 'locals' in a table

local lookuphashes = { }

setmetatableindex(lookuphashes, function(t,font)
    local lookuphash = fontdata[font].resources.lookuphash
    if not lookuphash or not next(lookuphash) then
        lookuphash = false
    end
    t[font] = lookuphash
    return lookuphash
end)

-- fonts.hashes.lookups = lookuphashes

local autofeatures = fonts.analyzers.features -- was: constants

local function initialize(sequence,script,language,enabled)
    local features = sequence.features
    if features then
        local order = sequence.order
        if order then
            for i=1,#order do --
                local kind = order[i] --
                local valid = enabled[kind]
                if valid then
                    local scripts = features[kind] --
                    local languages = scripts[script] or scripts[wildcard]
                    if languages and (languages[language] or languages[wildcard]) then
                        return { valid, autofeatures[kind] or false, sequence.chain or 0, kind, sequence }
                    end
                end
            end
        else
            -- can't happen
        end
    end
    return false
end

function otf.dataset(tfmdata,font) -- generic variant, overloaded in context
    local shared     = tfmdata.shared
    local properties = tfmdata.properties
    local language   = properties.language or "dflt"
    local script     = properties.script   or "dflt"
    local enabled    = shared.features
    local res = resolved[font]
    if not res then
        res = { }
        resolved[font] = res
    end
    local rs = res[script]
    if not rs then
        rs = { }
        res[script] = rs
    end
    local rl = rs[language]
    if not rl then
        rl = {
            -- indexed but we can also add specific data by key
        }
        rs[language] = rl
        local sequences = tfmdata.resources.sequences
        for s=1,#sequences do
            local v = enabled and initialize(sequences[s],script,language,enabled)
            if v then
                rl[#rl+1] = v
            end
        end
    end
    return rl
end

-- elseif id == glue_code then
--     if p[5] then -- chain
--         local pc = pp[32]
--         if pc then
--             start, ok = start, false -- p[1](start,kind,p[2],pc,p[3],p[4])
--             if ok then
--                 done = true
--             end
--             if start then start = getnext(start) end
--         else
--             start = getnext(start)
--         end
--     else
--         start = getnext(start)
--     end

-- there will be a new direction parser (pre-parsed etc)

-- less bytecode: 290 -> 254
--
-- attr = attr or false
--
-- local a = getattr(start,0)
-- if (a == attr and (not attribute or getprop(start,a_state) == attribute)) or (not attribute or getprop(start,a_state) == attribute) then
--     -- the action
-- end

-- assumptions:
--
-- * languages that use complex disc nodes

-- optimization comes later ...

local function kernrun(disc,run) -- we can assume that prev and next are glyphs
    if trace_kernruns then
        report_run("kern") -- will be more detailed
    end
        --
    local prev = getprev(disc) -- todo, keep these in the main loop
    local next = getnext(disc) -- todo, keep these in the main loop
    --
    local pre = getfield(disc,"pre")
    if not pre then
        -- go on
    elseif prev then
        local nest = getprev(pre)
        setfield(pre,"prev",prev)
        setfield(prev,"next",pre)
        run(prev,"preinjections")
        setfield(pre,"prev",nest)
        setfield(prev,"next",disc)
    else
        run(pre,"preinjections")
    end
    --
    local post = getfield(disc,"post")
    if not post then
        -- go on
    elseif next then
        local tail = find_node_tail(post)
        setfield(tail,"next",next)
        setfield(next,"prev",tail)
        run(post,"postinjections",tail)
        setfield(tail,"next",nil)
        setfield(next,"prev",disc)
    else
        run(post,"postinjections")
    end
    --
    local replace = getfield(disc,"replace")
    if not replace then
        -- this should be already done by discfound
    elseif prev and next then
        local tail = find_node_tail(replace)
        local nest = getprev(replace)
        setfield(replace,"prev",prev)
        setfield(prev,"next",replace)
        setfield(tail,"next",next)
        setfield(next,"prev",tail)
        run(prev,"replaceinjections",tail)
        setfield(replace,"prev",nest)
        setfield(prev,"next",disc)
        setfield(tail,"next",nil)
        setfield(next,"prev",disc)
    elseif prev then
        local nest = getprev(replace)
        setfield(replace,"prev",prev)
        setfield(prev,"next",replace)
        run(prev,"replaceinjections")
        setfield(replace,"prev",nest)
        setfield(prev,"next",disc)
    elseif next then
        local tail = find_node_tail(replace)
        setfield(tail,"next",next)
        setfield(next,"prev",tail)
        run(replace,"replaceinjections",tail)
        setfield(tail,"next",nil)
        setfield(next,"prev",disc)
    else
        run(replace,"replaceinjections")
    end
end

-- the if new test might be dangerous as luatex will check / set some tail stuff
-- in a temp node

local function comprun(disc,run)
    if trace_compruns then
        report_run("comp: %s",languages.serializediscretionary(disc))
    end
    --
    local pre = getfield(disc,"pre")
    if pre then
        local new, done = run(pre)
        if done then
            setfield(disc,"pre",new)
        end
    end
    --
    local post = getfield(disc,"post")
    if post then
        local new, done = run(post)
        if done then
            setfield(disc,"post",new)
        end
    end
    --
    local replace = getfield(disc,"replace")
    if replace then
        local new, done = run(replace)
        if done then
            setfield(disc,"replace",new)
        end
    end
end

local function testrun(disc,trun,crun)
    local next = getnext(disc)
    if next then
        local replace = getfield(disc,"replace")
        if replace then
            local prev = getprev(disc)
            if prev then
                -- only look ahead
                local tail = find_node_tail(replace)
             -- local nest = getprev(replace)
                setfield(tail,"next",next)
                setfield(next,"prev",tail)
                if trun(replace,next) then
                    setfield(disc,"replace",nil) -- beware, side effects of nest so first
                    setfield(prev,"next",replace)
                    setfield(replace,"prev",prev)
                    setfield(next,"prev",tail)
                    setfield(tail,"next",next)
                    setfield(disc,"prev",nil)
                    setfield(disc,"next",nil)
                    flush_node_list(disc)
                    return replace -- restart
                else
                    setfield(tail,"next",nil)
                    setfield(next,"prev",disc)
                end
            else
                -- weird case
            end
        else
            -- no need
        end
    else
        -- weird case
    end
    comprun(disc,crun)
    return next
end

local function discrun(disc,drun,krun)
    local next = getnext(disc)
    local prev = getprev(disc)
    if trace_discruns then
        report_run("disc") -- will be more detailed
    end
    if next and prev then
        setfield(prev,"next",next)
     -- setfield(next,"prev",prev)
        drun(prev)
        setfield(prev,"next",disc)
     -- setfield(next,"prev",disc)
    end
    --
    local pre = getfield(disc,"pre")
    if not pre then
        -- go on
    elseif prev then
        local nest = getprev(pre)
        setfield(pre,"prev",prev)
        setfield(prev,"next",pre)
        krun(prev,"preinjections")
        setfield(pre,"prev",nest)
        setfield(prev,"next",disc)
    else
        krun(pre,"preinjections")
    end
    return next
end

-- todo: maybe run lr and rl stretches

local function featuresprocessor(head,font,attr)

    local lookuphash = lookuphashes[font] -- we can also check sequences here

    if not lookuphash then
        return head, false
    end

    head = tonut(head)

    if trace_steps then
        checkstep(head)
    end

    tfmdata         = fontdata[font]
    descriptions    = tfmdata.descriptions
    characters      = tfmdata.characters
    resources       = tfmdata.resources

    marks           = resources.marks
    anchorlookups   = resources.lookup_to_anchor
    lookuptable     = resources.lookups
    lookuptypes     = resources.lookuptypes
    lookuptags      = resources.lookuptags

    currentfont     = font
    rlmode          = 0

    local sequences = resources.sequences
    local done      = false
    local datasets  = otf.dataset(tfmdata,font,attr)

    local dirstack  = { } -- could move outside function

    -- We could work on sub start-stop ranges instead but I wonder if there is that
    -- much speed gain (experiments showed that it made not much sense) and we need
    -- to keep track of directions anyway. Also at some point I want to play with
    -- font interactions and then we do need the full sweeps.

    -- Keeping track of the headnode is needed for devanagari (I generalized it a bit
    -- so that multiple cases are also covered.)

    -- todo: retain prev

    -- We don't goto the next node of a disc node is created so that we can then treat
    -- the pre, post and replace. It's abit of a hack but works out ok for most cases.

    -- there can be less subtype and attr checking in the comprun etc helpers

    for s=1,#datasets do
        local dataset      = datasets[s]
              featurevalue = dataset[1] -- todo: pass to function instead of using a global
        local attribute    = dataset[2]
        local chain        = dataset[3] -- sequence.chain or 0
        local kind         = dataset[4]
        local sequence     = dataset[5] -- sequences[s] -- also dataset[5]
        local rlparmode    = 0
        local topstack     = 0
        local success      = false
        local typ          = sequence.type
        local gpossing     = typ == "gpos_single" or typ == "gpos_pair"
        local subtables    = sequence.subtables
        local handler      = handlers[typ]

        if chain < 0 then
            -- this is a limited case, no special treatments like 'init' etc
            -- we need to get rid of this slide! probably no longer needed in latest luatex
            local start = find_node_tail(head) -- slow (we can store tail because there's always a skip at the end): todo
            while start do
                local id = getid(start)
                if id == glyph_code then
                    if getfont(start) == font and getsubtype(start) < 256 then
                        local a = getattr(start,0)
                        if a then
                            a = a == attr
                        else
                            a = true
                        end
                        if a then
                            local char = getchar(start)
                            for i=1,#subtables do
                                local lookupname = subtables[i]
                                local lookupcache = lookuphash[lookupname]
                                if lookupcache then
                                 -- local lookupmatch = lookupcache[getchar(start)]
                                    local lookupmatch = lookupcache[start]
                                    if lookupmatch then
                                        -- todo: disc?
                                        head, start, success = handler(head,start,kind,lookupname,lookupmatch,sequence,lookuphash,i)
                                        if success then
                                            break
                                        end
                                    end
                                else
                                    report_missing_cache(typ,lookupname)
                                end
                            end
                            if start then start = getprev(start) end
                        else
                            start = getprev(start)
                        end
                    else
                        start = getprev(start)
                    end
                else
                    start = getprev(start)
                end
            end
        else
            local ns = #subtables
            local start = head -- local ?
            rlmode = 0 -- to be checked ?
            if ns == 1 then -- happens often
                local lookupname = subtables[1]
                local lookupcache = lookuphash[lookupname]
                if not lookupcache then -- also check for empty cache
                    report_missing_cache(typ,lookupname)
                else

                    local function c_run(start) -- no need to check for 256 and attr probably also the same
                        local head = start
                        local done = false
                        while start do
                            local id = getid(start)
                            if id ~= glyph_code then
                                -- very unlikely
                                start = getnext(start)
                            elseif getfont(start) == font and getsubtype(start) < 256 then
                                local a = getattr(start,0)
                                if a then
                                    a = (a == attr) and (not attribute or getprop(start,a_state) == attribute)
                                else
                                    a = not attribute or getprop(start,a_state) == attribute
                                end
                                if a then
                                    local lookupmatch = lookupcache[getchar(start)]
                                    if lookupmatch then
                                        -- sequence kan weg
                                        local ok
                                        head, start, ok = handler(head,start,kind,lookupname,lookupmatch,sequence,lookuphash,1)
                                        if ok then
                                            done = true
                                        end
                                    end
                                    if start then start = getnext(start) end
                                else
                                    start = getnext(start)
                                end
                            else
                                return head, false
                            end
                        end
                        if done then
                            success = true -- needed in this subrun?
                        end
                        return head, done
                    end

                    local function t_run(start,stop)
                        while start ~= stop do
                            local id = getid(start)
                            if id == glyph_code and getfont(start) == font and getsubtype(start) < 256 then
                                local a = getattr(start,0)
                                if a then
                                    a = (a == attr) and (not attribute or getprop(start,a_state) == attribute)
                                else
                                    a = not attribute or getprop(start,a_state) == attribute
                                end
                                if a then
                                    local lookupmatch = lookupcache[getchar(start)]
                                    if lookupmatch then -- hm, hyphens can match (tlig) so we need to really check
                                        -- if we need more than ligatures we can outline the code and use functions
                                        local s = getnext(start)
                                        local l = nil
                                        while s do
                                            local lg = lookupmatch[getchar(s)]
                                            if lg then
                                                l = lg
                                                s = getnext(s)
                                            else
                                                break
                                            end
                                        end
                                        if l and l.ligature then
                                            return true
                                        end
                                    end
                                end
                                start = getnext(start)
                            else
                                break
                            end
                        end
                    end

                    local function d_run(prev) -- we can assume that prev and next are glyphs
                        local a = getattr(prev,0)
                        if a then
                            a = (a == attr) and (not attribute or getprop(prev,a_state) == attribute)
                        else
                            a = not attribute or getprop(prev,a_state) == attribute
                        end
                        if a then
                            local lookupmatch = lookupcache[getchar(prev)]
                            if lookupmatch then
                                -- sequence kan weg
                                local h, d, ok = handler(head,prev,kind,lookupname,lookupmatch,sequence,lookuphash,1)
                                if ok then
                                    done = true
                                    success = true
                                end
                            end
                        end
                    end

                    local function k_run(sub,injection,last)
                        local a = getattr(sub,0)
                        if a then
                            a = (a == attr) and (not attribute or getprop(sub,a_state) == attribute)
                        else
                            a = not attribute or getprop(sub,a_state) == attribute
                        end
                        if a then
                            -- sequence kan weg
                            for n in traverse_nodes(sub) do -- only gpos
                                if n == last then
                                    break
                                end
                                local id = getid(n)
                                if id == glyph_code then
                                    local lookupmatch = lookupcache[getchar(n)]
                                    if lookupmatch then
                                        local h, d, ok = handler(sub,n,kind,lookupname,lookupmatch,sequence,lookuphash,1,injection)
                                        if ok then
                                            done = true
                                            success = true
                                        end
                                    end
                                else
                                    -- message
                                end
                            end
                        end
                    end

                    while start do
                        local id = getid(start)
                        if id == glyph_code then
                            if getfont(start) == font and getsubtype(start) < 256 then -- why a 256 test ...
                                local a = getattr(start,0)
                                if a then
                                    a = (a == attr) and (not attribute or getprop(start,a_state) == attribute)
                                else
                                    a = not attribute or getprop(start,a_state) == attribute
                                end
                                if a then
                                    local char        = getchar(start)
                                    local lookupmatch = lookupcache[char]
                                    if lookupmatch then
                                        -- sequence kan weg
                                        local ok
                                        head, start, ok = handler(head,start,kind,lookupname,lookupmatch,sequence,lookuphash,1)
                                        if ok then
                                            success = true
                                        elseif gpossing and zwnjruns and char == zwnj then
                                            discrun(start,d_run)
                                        end
                                    elseif gpossing and zwnjruns and char == zwnj then
                                        discrun(start,d_run)
                                    end
                                    if start then start = getnext(start) end
                                else
                                   start = getnext(start)
                                end
                            else
                                start = getnext(start)
                            end
                        elseif id == disc_code then
                           local discretionary = getsubtype(start) == discretionary_code
                           if gpossing then
                               if discretionary then
                                   kernrun(start,k_run)
                               else
                                   discrun(start,d_run,k_run)
                               end
                               start = getnext(start)
                           elseif discretionary then
                               if typ == "gsub_ligature" then
                                   start = testrun(start,t_run,c_run)
                               else
                                   comprun(start,c_run)
                                   start = getnext(start)
                               end
                           else
                                start = getnext(start)
                           end
                        elseif id == whatsit_code then -- will be function
                            local subtype = getsubtype(start)
                            if subtype == dir_code then
                                local dir = getfield(start,"dir")
                                if     dir == "+TRT" or dir == "+TLT" then
                                    topstack = topstack + 1
                                    dirstack[topstack] = dir
                                elseif dir == "-TRT" or dir == "-TLT" then
                                    topstack = topstack - 1
                                end
                                local newdir = dirstack[topstack]
                                if newdir == "+TRT" then
                                    rlmode = -1
                                elseif newdir == "+TLT" then
                                    rlmode = 1
                                else
                                    rlmode = rlparmode
                                end
                                if trace_directions then
                                    report_process("directions after txtdir %a: parmode %a, txtmode %a, # stack %a, new dir %a",dir,rlparmode,rlmode,topstack,newdir)
                                end
                            elseif subtype == localpar_code then
                                local dir = getfield(start,"dir")
                                if dir == "TRT" then
                                    rlparmode = -1
                                elseif dir == "TLT" then
                                    rlparmode = 1
                                else
                                    rlparmode = 0
                                end
                                -- one might wonder if the par dir should be looked at, so we might as well drop the next line
                                rlmode = rlparmode
                                if trace_directions then
                                    report_process("directions after pardir %a: parmode %a, txtmode %a",dir,rlparmode,rlmode)
                                end
                            end
                            start = getnext(start)
                        elseif id == math_code then
                            start = getnext(end_of_math(start))
                        else
                            start = getnext(start)
                        end
                    end
                end

            else

                local function c_run(start)
                    local head = start
                    local done = false
                    while start do
                        local id = getid(start)
                        if id ~= glyph_code then
                            -- very unlikely
                            start = getnext(start)
                        elseif getfont(start) == font and getsubtype(start) < 256 then
                            local a = getattr(start,0)
                            if a then
                                a = (a == attr) and (not attribute or getprop(start,a_state) == attribute)
                            else
                                a = not attribute or getprop(start,a_state) == attribute
                            end
                            if a then
                                local char = getchar(start)
                                for i=1,ns do
                                    local lookupname = subtables[i]
                                    local lookupcache = lookuphash[lookupname]
                                    if lookupcache then
                                     -- local lookupmatch = lookupcache[getchar(start)]
                                        local lookupmatch = lookupcache[char]
                                        if lookupmatch then
                                            -- we could move all code inline but that makes things even more unreadable
                                            local ok
                                            head, start, ok = handler(head,start,kind,lookupname,lookupmatch,sequence,lookuphash,i)
                                            if ok then
                                                done = true
                                                break
                                            elseif not start then
                                                -- don't ask why ... shouldn't happen
                                                break
                                            end
                                        end
                                    else
                                        report_missing_cache(typ,lookupname)
                                    end
                                end
                                if start then start = getnext(start) end
                            else
                                start = getnext(start)
                            end
                        else
                            return head, false
                        end
                    end
                    if done then
                        success = true
                    end
                    return head, done
                end

                local function d_run(prev)
                    local a = getattr(prev,0)
                    if a then
                        a = (a == attr) and (not attribute or getprop(prev,a_state) == attribute)
                    else
                        a = not attribute or getprop(prev,a_state) == attribute
                    end
                    if a then
                        -- brr prev can be disc
                        local char = getchar(prev)
                        for i=1,ns do
                            local lookupname = subtables[i]
                            local lookupcache = lookuphash[lookupname]
                            if lookupcache then
                                local lookupmatch = lookupcache[char]
                                if lookupmatch then
                                    -- we could move all code inline but that makes things even more unreadable
                                    local h, d, ok = handler(head,prev,kind,lookupname,lookupmatch,sequence,lookuphash,i)
                                    if ok then
                                        done = true
                                        break
                                    end
                                end
                            else
                                report_missing_cache(typ,lookupname)
                            end
                        end
                    end
                end

               local function k_run(sub,injection,last)
                    local a = getattr(sub,0)
                    if a then
                        a = (a == attr) and (not attribute or getprop(sub,a_state) == attribute)
                    else
                        a = not attribute or getprop(sub,a_state) == attribute
                    end
                    if a then
                        for n in traverse_nodes(sub) do -- only gpos
                            if n == last then
                                break
                            end
                            local id = getid(n)
                            if id == glyph_code then
                                local char = getchar(n)
                                for i=1,ns do
                                    local lookupname = subtables[i]
                                    local lookupcache = lookuphash[lookupname]
                                    if lookupcache then
                                        local lookupmatch = lookupcache[char]
                                        if lookupmatch then
                                            local h, d, ok = handler(head,n,kind,lookupname,lookupmatch,sequence,lookuphash,i,injection)
                                            if ok then
                                                done = true
                                                break
                                            end
                                        end
                                    else
                                        report_missing_cache(typ,lookupname)
                                    end
                                end
                            else
                                -- message
                            end
                        end
                    end
                end

                local function t_run(start,stop)
                    while start ~= stop do
                        local id = getid(start)
                        if id == glyph_code and getfont(start) == font and getsubtype(start) < 256 then
                            local a = getattr(start,0)
                            if a then
                                a = (a == attr) and (not attribute or getprop(start,a_state) == attribute)
                            else
                                a = not attribute or getprop(start,a_state) == attribute
                            end
                            if a then
                                local char = getchar(start)
                                for i=1,ns do
                                    local lookupname = subtables[i]
                                    local lookupcache = lookuphash[lookupname]
                                    if lookupcache then
                                        local lookupmatch = lookupcache[char]
                                        if lookupmatch then
                                            -- if we need more than ligatures we can outline the code and use functions
                                            local s = getnext(start)
                                            local l = nil
                                            while s do
                                                local lg = lookupmatch[getchar(s)]
                                                if lg then
                                                    l = lg
                                                    s = getnext(s)
                                                else
                                                    break
                                                end
                                            end
                                            if l and l.ligature then
                                                return true
                                            end
                                        end
                                    else
                                        report_missing_cache(typ,lookupname)
                                    end
                                end
                            end
                            start = getnext(start)
                        else
                            break
                        end
                    end
                end

                while start do
                    local id = getid(start)
                    if id == glyph_code then
                        if getfont(start) == font and getsubtype(start) < 256 then
                            local a = getattr(start,0)
                            if a then
                                a = (a == attr) and (not attribute or getprop(start,a_state) == attribute)
                            else
                                a = not attribute or getprop(start,a_state) == attribute
                            end
                            if a then
                                for i=1,ns do
                                    local lookupname = subtables[i]
                                    local lookupcache = lookuphash[lookupname]
                                    if lookupcache then
                                        local char = getchar(start)
                                        local lookupmatch = lookupcache[char]
                                        if lookupmatch then
                                            -- we could move all code inline but that makes things even more unreadable
                                            local ok
                                            head, start, ok = handler(head,start,kind,lookupname,lookupmatch,sequence,lookuphash,i)
                                            if ok then
                                                success = true
                                                break
                                            elseif not start then
                                                -- don't ask why ... shouldn't happen
                                                break
                                            elseif gpossing and zwnjruns and char == zwnj then
                                                discrun(start,d_run)
                                            end
                                        elseif gpossing and zwnjruns and char == zwnj then
                                            discrun(start,d_run)
                                        end
                                    else
                                        report_missing_cache(typ,lookupname)
                                    end
                                end
                                if start then start = getnext(start) end
                            else
                                start = getnext(start)
                            end
                        else
                            start = getnext(start)
                        end
                    elseif id == disc_code then
                        local discretionary = getsubtype(start) == discretionary_code
                        if gpossing then
                            if discretionary then
                                kernrun(start,k_run)
                            else
                                discrun(start,d_run,k_run)
                            end
                            start = getnext(start)
                        elseif discretionary then
                            if typ == "gsub_ligature" then
                                start = testrun(start,t_run,c_run)
                            else
                                comprun(start,c_run)
                                start = getnext(start)
                            end
                        else
                            start = getnext(start)
                        end
                    elseif id == whatsit_code then
                        local subtype = getsubtype(start)
                        if subtype == dir_code then
                            local dir = getfield(start,"dir")
                            if     dir == "+TRT" or dir == "+TLT" then
                                topstack = topstack + 1
                                dirstack[topstack] = dir
                            elseif dir == "-TRT" or dir == "-TLT" then
                                topstack = topstack - 1
                            end
                            local newdir = dirstack[topstack]
                            if newdir == "+TRT" then
                                rlmode = -1
                            elseif newdir == "+TLT" then
                                rlmode = 1
                            else
                                rlmode = rlparmode
                            end
                            if trace_directions then
                                report_process("directions after txtdir %a: parmode %a, txtmode %a, # stack %a, new dir %a",dir,rlparmode,rlmode,topstack,newdir)
                            end
                        elseif subtype == localpar_code then
                            local dir = getfield(start,"dir")
                            if dir == "TRT" then
                                rlparmode = -1
                            elseif dir == "TLT" then
                                rlparmode = 1
                            else
                                rlparmode = 0
                            end
                            rlmode = rlparmode
                            if trace_directions then
                                report_process("directions after pardir %a: parmode %a, txtmode %a",dir,rlparmode,rlmode)
                            end
                        end
                        start = getnext(start)
                    elseif id == math_code then
                        start = getnext(end_of_math(start))
                    else
                        start = getnext(start)
                    end
                end
            end
        end
        if success then
            done = true
        end
        if trace_steps then -- ?
            registerstep(head)
        end

    end

    head = tonode(head)

    return head, done
end

local function generic(lookupdata,lookupname,unicode,lookuphash)
    local target = lookuphash[lookupname]
    if target then
        target[unicode] = lookupdata
    else
        lookuphash[lookupname] = { [unicode] = lookupdata }
    end
end

local action = {

    substitution = generic,
    multiple     = generic,
    alternate    = generic,
    position     = generic,

    ligature = function(lookupdata,lookupname,unicode,lookuphash)
        local target = lookuphash[lookupname]
        if not target then
            target = { }
            lookuphash[lookupname] = target
        end
        for i=1,#lookupdata do
            local li = lookupdata[i]
            local tu = target[li]
            if not tu then
                tu = { }
                target[li] = tu
            end
            target = tu
        end
        target.ligature = unicode
    end,

    pair = function(lookupdata,lookupname,unicode,lookuphash)
        local target = lookuphash[lookupname]
        if not target then
            target = { }
            lookuphash[lookupname] = target
        end
        local others = target[unicode]
        local paired = lookupdata[1]
        if others then
            others[paired] = lookupdata
        else
            others = { [paired] = lookupdata }
            target[unicode] = others
        end
    end,

}

local function prepare_lookups(tfmdata)

    local rawdata          = tfmdata.shared.rawdata
    local resources        = rawdata.resources
    local lookuphash       = resources.lookuphash
    local anchor_to_lookup = resources.anchor_to_lookup
    local lookup_to_anchor = resources.lookup_to_anchor
    local lookuptypes      = resources.lookuptypes
    local characters       = tfmdata.characters
    local descriptions     = tfmdata.descriptions

    -- we cannot free the entries in the descriptions as sometimes we access
    -- then directly (for instance anchors) ... selectively freeing does save
    -- much memory as it's only a reference to a table and the slot in the
    -- description hash is not freed anyway

    for unicode, character in next, characters do -- we cannot loop over descriptions !

        local description = descriptions[unicode]

        if description then

            local lookups = description.slookups
            if lookups then
                for lookupname, lookupdata in next, lookups do
                    action[lookuptypes[lookupname]](lookupdata,lookupname,unicode,lookuphash)
                end
            end

            local lookups = description.mlookups
            if lookups then
                for lookupname, lookuplist in next, lookups do
                    local lookuptype = lookuptypes[lookupname]
                    for l=1,#lookuplist do
                        local lookupdata = lookuplist[l]
                        action[lookuptype](lookupdata,lookupname,unicode,lookuphash)
                    end
                end
            end

            local list = description.kerns
            if list then
                for lookup, krn in next, list do  -- ref to glyph, saves lookup
                    local target = lookuphash[lookup]
                    if target then
                        target[unicode] = krn
                    else
                        lookuphash[lookup] = { [unicode] = krn }
                    end
                end
            end

            local list = description.anchors
            if list then
                for typ, anchors in next, list do -- types
                    if typ == "mark" or typ == "cexit" then -- or entry?
                        for name, anchor in next, anchors do
                            local lookups = anchor_to_lookup[name]
                            if lookups then
                                for lookup, _ in next, lookups do
                                    local target = lookuphash[lookup]
                                    if target then
                                        target[unicode] = anchors
                                    else
                                        lookuphash[lookup] = { [unicode] = anchors }
                                    end
                                end
                            end
                        end
                    end
                end
            end

        end

    end

end

local function split(replacement,original)
    local result = { }
    for i=1,#replacement do
        result[original[i]] = replacement[i]
    end
    return result
end

local valid = {
    coverage        = { chainsub = true, chainpos = true, contextsub = true },
    reversecoverage = { reversesub = true },
    glyphs          = { chainsub = true, chainpos = true },
}

local function prepare_contextchains(tfmdata)
    local rawdata    = tfmdata.shared.rawdata
    local resources  = rawdata.resources
    local lookuphash = resources.lookuphash
    local lookuptags = resources.lookuptags
    local lookups    = rawdata.lookups
    if lookups then
        for lookupname, lookupdata in next, rawdata.lookups do
            local lookuptype = lookupdata.type
            if lookuptype then
                local rules = lookupdata.rules
                if rules then
                    local format = lookupdata.format
                    local validformat = valid[format]
                    if not validformat then
                        report_prepare("unsupported format %a",format)
                    elseif not validformat[lookuptype] then
                        -- todo: dejavu-serif has one (but i need to see what use it has)
                        report_prepare("unsupported format %a, lookuptype %a, lookupname %a",format,lookuptype,lookuptags[lookupname])
                    else
                        local contexts = lookuphash[lookupname]
                        if not contexts then
                            contexts = { }
                            lookuphash[lookupname] = contexts
                        end
                        local t, nt = { }, 0
                        for nofrules=1,#rules do
                            local rule         = rules[nofrules]
                            local current      = rule.current
                            local before       = rule.before
                            local after        = rule.after
                            local replacements = rule.replacements
                            local sequence     = { }
                            local nofsequences = 0
                            -- Eventually we can store start, stop and sequence in the cached file
                            -- but then less sharing takes place so best not do that without a lot
                            -- of profiling so let's forget about it.
                            if before then
                                for n=1,#before do
                                    nofsequences = nofsequences + 1
                                    sequence[nofsequences] = before[n]
                                end
                            end
                            local start = nofsequences + 1
                            for n=1,#current do
                                nofsequences = nofsequences + 1
                                sequence[nofsequences] = current[n]
                            end
                            local stop = nofsequences
                            if after then
                                for n=1,#after do
                                    nofsequences = nofsequences + 1
                                    sequence[nofsequences] = after[n]
                                end
                            end
                            if sequence[1] then
                                -- Replacements only happen with reverse lookups as they are single only. We
                                -- could pack them into current (replacement value instead of true) and then
                                -- use sequence[start] instead but it's somewhat ugly.
                                nt = nt + 1
                                t[nt] = { nofrules, lookuptype, sequence, start, stop, rule.lookups, replacements }
                                for unic, _  in next, sequence[start] do
                                    local cu = contexts[unic]
                                    if not cu then
                                        contexts[unic] = t
                                    end
                                end
                            end
                        end
                    end
                else
                    -- no rules
                end
            else
                report_prepare("missing lookuptype for lookupname %a",lookuptags[lookupname])
            end
        end
    end
end

-- we can consider lookuphash == false (initialized but empty) vs lookuphash == table

local function featuresinitializer(tfmdata,value)
    if true then -- value then
        -- beware we need to use the topmost properties table
        local rawdata    = tfmdata.shared.rawdata
        local properties = rawdata.properties
        if not properties.initialized then
            local starttime = trace_preparing and os.clock()
            local resources = rawdata.resources
            resources.lookuphash = resources.lookuphash or { }
            prepare_contextchains(tfmdata)
            prepare_lookups(tfmdata)
            properties.initialized = true
            if trace_preparing then
                report_prepare("preparation time is %0.3f seconds for %a",os.clock()-starttime,tfmdata.properties.fullname)
            end
        end
    end
end

registerotffeature {
    name         = "features",
    description  = "features",
    default      = true,
    initializers = {
        position = 1,
        node     = featuresinitializer,
    },
    processors   = {
        node     = featuresprocessor,
    }
}

-- This can be used for extra handlers, but should be used with care!

otf.handlers = handlers