summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/tex/context/base/mkiv/font-dsp.lua
blob: d43348cdfb1c9d57f948b450b77d2ab6452c90e1 (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
if not modules then modules = { } end modules ['font-dsp'] = {
    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"
}

-- many 0,0 entry/exit

-- This loader went through a few iterations. First I made a ff compatible one so
-- that we could do some basic checking. Also some verbosity was added (named
-- glyphs). Eventually all that was dropped for a context friendly format, simply
-- because keeping the different table models in sync too to much time. I have the
-- old file somewhere. A positive side effect is that we get an (upto) much smaller
-- smaller tma/tmc file. In the end the loader will be not much slower than the
-- c based ff one.

-- Being binary encoded, an opentype is rather compact. When expanded into a Lua table
-- quite some memory can be used. This is very noticeable in the ff loader, which for
-- a good reason uses a verbose format. However, when we use that data we create a couple
-- of hashes. In the Lua loader we create these hashes directly, which save quite some
-- memory.
--
-- We convert a font file only once and then cache it. Before creating the cached instance
-- packing takes place: common tables get shared. After (re)loading and unpacking we then
-- get a rather efficient internal representation of the font. In the new loader there is a
-- pitfall. Because we use some common coverage magic we put a bit more information in
-- the mark and cursive coverage tables than strickly needed: a reference to the coverage
-- itself. This permits a fast lookup of the second glyph involved. In the marks we
-- expand the class indicator to a class hash, in the cursive we use a placeholder that gets
-- a self reference. This means that we cannot pack these subtables unless we add a unique
-- id per entry (the same one per coverage) and that makes the tables larger. Because only a
-- few fonts benefit from this, I decided to not do this. Experiments demonstrated that it
-- only gives a few percent gain (on for instance husayni we can go from 845K to 828K
-- bytecode). Better stay conceptually clean than messy compact.

-- When we can reduce all basic lookups to one step we might safe a bit in the processing
-- so then only chains are multiple.

-- I used to flatten kerns here but that has been moved elsewhere because it polutes the code
-- here and can be done fast afterwards. One can even wonder if it makes sense to do it as we
-- pack anyway. In a similar fashion the unique placeholders in anchors in marks have been
-- removed because packing doesn't save much there anyway.

-- Although we have a bit more efficient tables in the cached files, the internals are still
-- pretty similar. And although we have a slightly more direct coverage access the processing
-- of node lists is not noticeable faster for latin texts, but for arabic we gain some 10%
-- (and could probably gain a bit more).

-- All this packing in the otf format is somewhat obsessive as nowadays 4K resolution
-- multi-gig videos pass through our networks and storage and memory is abundant.

local next, type = next, type
local bittest = bit32.btest
local band = bit32.band
local extract = bit32.extract
local bor = bit32.bor
local lshift = bit32.lshift
local rshift = bit32.rshift
local gsub = string.gsub
local lower = string.lower
local sub = string.sub
local strip = string.strip
local tohash = table.tohash
local concat = table.concat
local copy = table.copy
local reversed = table.reversed
local sort = table.sort
local insert = table.insert
local round = math.round
local lpegmatch = lpeg.match

local setmetatableindex = table.setmetatableindex
local formatters        = string.formatters
local sortedkeys        = table.sortedkeys
local sortedhash        = table.sortedhash

local report            = logs.reporter("otf reader")

local readers           = fonts.handlers.otf.readers
local streamreader      = readers.streamreader

local setposition       = streamreader.setposition
local getposition       = streamreader.getposition
local readushort        = streamreader.readcardinal2  -- 16-bit unsigned integer
local readulong         = streamreader.readcardinal4  -- 24-bit unsigned integer
local readinteger       = streamreader.readinteger1
local readshort         = streamreader.readinteger2   -- 16-bit   signed integer
local readstring        = streamreader.readstring
local readtag           = streamreader.readtag
local readbytes         = streamreader.readbytes
local readfixed         = streamreader.readfixed4
local read2dot14        = streamreader.read2dot14
local skipshort         = streamreader.skipshort
local skipbytes         = streamreader.skip
local readfword         = readshort
local readbytetable     = streamreader.readbytetable
local readbyte          = streamreader.readbyte

local gsubhandlers      = { }
local gposhandlers      = { }

readers.gsubhandlers    = gsubhandlers
readers.gposhandlers    = gposhandlers

local helpers           = readers.helpers
local gotodatatable     = helpers.gotodatatable
local setvariabledata   = helpers.setvariabledata

local lookupidoffset    = -1    -- will become 1 when we migrate (only -1 for comparign with old)

local classes = {
    "base",
    "ligature",
    "mark",
    "component",
}

local gsubtypes = {
    "single",
    "multiple",
    "alternate",
    "ligature",
    "context",
    "chainedcontext",
    "extension",
    "reversechainedcontextsingle",
}

local gpostypes = {
    "single",
    "pair",
    "cursive",
    "marktobase",
    "marktoligature",
    "marktomark",
    "context",
    "chainedcontext",
    "extension",
}

local chaindirections = {
    context                     =  0,
    chainedcontext              =  1,
    reversechainedcontextsingle = -1,
}

local function setmetrics(data,where,tag,d)
    local w = data[where]
    if w then
        local v = w[tag]
        if v then
            -- it looks like some fonts set the value and not the delta
         -- report("adding %s to %s.%s value %s",d,where,tag,v)
            w[tag] = v + d
        end
    end
end

local variabletags = {
    hasc = function(data,d) setmetrics(data,"windowsmetrics","typoascender",d) end,
    hdsc = function(data,d) setmetrics(data,"windowsmetrics","typodescender",d) end,
    hlgp = function(data,d) setmetrics(data,"windowsmetrics","typolinegap",d) end,
    hcla = function(data,d) setmetrics(data,"windowsmetrics","winascent",d) end,
    hcld = function(data,d) setmetrics(data,"windowsmetrics","windescent",d) end,
    vasc = function(data,d) setmetrics(data,"vhea not done","ascent",d) end,
    vdsc = function(data,d) setmetrics(data,"vhea not done","descent",d) end,
    vlgp = function(data,d) setmetrics(data,"vhea not done","linegap",d) end,
    xhgt = function(data,d) setmetrics(data,"windowsmetrics","xheight",d) end,
    cpht = function(data,d) setmetrics(data,"windowsmetrics","capheight",d) end,
    sbxs = function(data,d) setmetrics(data,"windowsmetrics","subscriptxsize",d) end,
    sbys = function(data,d) setmetrics(data,"windowsmetrics","subscriptysize",d) end,
    sbxo = function(data,d) setmetrics(data,"windowsmetrics","subscriptxoffset",d) end,
    sbyo = function(data,d) setmetrics(data,"windowsmetrics","subscriptyoffset",d) end,
    spxs = function(data,d) setmetrics(data,"windowsmetrics","superscriptxsize",d) end,
    spys = function(data,d) setmetrics(data,"windowsmetrics","superscriptysize",d) end,
    spxo = function(data,d) setmetrics(data,"windowsmetrics","superscriptxoffset",d) end,
    spyo = function(data,d) setmetrics(data,"windowsmetrics","superscriptyoffset",d) end,
    strs = function(data,d) setmetrics(data,"windowsmetrics","strikeoutsize",d) end,
    stro = function(data,d) setmetrics(data,"windowsmetrics","strikeoutpos",d) end,
    unds = function(data,d) setmetrics(data,"postscript","underlineposition",d) end,
    undo = function(data,d) setmetrics(data,"postscript","underlinethickness",d) end,
}

local read_cardinal = {
    streamreader.readcardinal1,
    streamreader.readcardinal2,
    streamreader.readcardinal3,
    streamreader.readcardinal4,
}

local read_integer = {
    streamreader.readinteger1,
    streamreader.readinteger2,
    streamreader.readinteger3,
    streamreader.readinteger4,
}

-- using helpers doesn't make much sense, subtle differences
--
-- local function readushortarray(f,n)
--     local t = { }
--     for i=1,n do
--         t[i] = readushort(f)
--     end
--     return t
-- end
--
-- local function readulongarray(f,n)
--     local t = { }
--     for i=1,n do
--         t[i] = readulong(f)
--     end
--     return t
-- end
--
-- local function readushortarray(f,target,first,size)
--     if not size then
--         for i=1,size do
--             target[i] = readushort(f)
--         end
--     else
--         for i=1,size do
--             target[first+i] = readushort(f)
--         end
--     end
--     return target
-- end
--
-- so we get some half helper - half non helper mix then

-- Traditionally we use these unique names (so that we can flatten the lookup list
-- (we create subsets runtime) but I will adapt the old code to newer names.

-- chainsub
-- reversesub

local lookupnames = {
    gsub = {
        single                      = "gsub_single",
        multiple                    = "gsub_multiple",
        alternate                   = "gsub_alternate",
        ligature                    = "gsub_ligature",
        context                     = "gsub_context",
        chainedcontext              = "gsub_contextchain",
        reversechainedcontextsingle = "gsub_reversecontextchain", -- reversesub
    },
    gpos = {
        single                      = "gpos_single",
        pair                        = "gpos_pair",
        cursive                     = "gpos_cursive",
        marktobase                  = "gpos_mark2base",
        marktoligature              = "gpos_mark2ligature",
        marktomark                  = "gpos_mark2mark",
        context                     = "gpos_context",
        chainedcontext              = "gpos_contextchain",
    }
}

-- keep this as reference:
--
-- local lookupbits = {
--     [0x0001] = "righttoleft",
--     [0x0002] = "ignorebaseglyphs",
--     [0x0004] = "ignoreligatures",
--     [0x0008] = "ignoremarks",
--     [0x0010] = "usemarkfilteringset",
--     [0x00E0] = "reserved",
--     [0xFF00] = "markattachmenttype",
-- }
--
-- local lookupstate = setmetatableindex(function(t,k)
--     local v = { }
--     for kk, vv in next, lookupbits do
--         if bittest(k,kk) then
--             v[vv] = true
--         end
--     end
--     t[k] = v
--     return v
-- end)

local lookupflags = setmetatableindex(function(t,k)
    local v = {
        bittest(k,0x0008) and true or false, -- ignoremarks
        bittest(k,0x0004) and true or false, -- ignoreligatures
        bittest(k,0x0002) and true or false, -- ignorebaseglyphs
        bittest(k,0x0001) and true or false, -- r2l
    }
    t[k] = v
    return v
end)

-- Variation stores: it's not entirely clear if the regions are a shared
-- resource (it looks like they are). Anyway, we play safe and use a
-- share.

-- values can be anything the min/max permits so we can either think of
-- real values of a fraction along the axis (probably easier)

-- wght:400,wdth:100,ital:1

-- local names = table.setmetatableindex ( {
--     weight = "wght",
--     width  = "wdth",
--     italic = "ital",
-- }, "self")

local pattern = lpeg.Cf (
    lpeg.Ct("") *
    lpeg.Cg (
      --(lpeg.R("az")^1/names) * lpeg.S(" :") *
        lpeg.C(lpeg.R("az")^1) * lpeg.S(" :=") *
        (lpeg.patterns.number/tonumber) * lpeg.S(" ,")^0
    )^1, rawset
)

local hash = table.setmetatableindex(function(t,k)
    local v = lpegmatch(pattern,k)
    local t = { }
    for k, v in sortedhash(v) do
        t[#t+1] = k .. "=" .. v
    end
    v = concat(t,",")
    t[k] = v
    return v
end)

helpers.normalizedaxishash = hash

local cleanname = fonts.names and fonts.names.cleanname or function(name)
    return name and (gsub(lower(name),"[^%a%d]","")) or nil
end

helpers.cleanname = cleanname

function helpers.normalizedaxis(str)
    return hash[str] or str
end

local function axistofactors(str)
    return lpegmatch(pattern,str)
end

-- contradicting spec ... (signs) so i'll check it and fix it once we have
-- proper fonts

local function getaxisscale(segments,minimum,default,maximum,user)
    --
    -- returns the right values cf example in standard
    --
    if not minimum or not default or not maximum then
        return false
    end
    if user < minimum then
        user = minimum
    elseif user > maximum then
        user = maximum
    end
    if user < default then
        default = - (default - user) / (default - minimum)
    elseif user > default then
        default = (user - default) / (maximum - default)
    else
        default = 0
    end
    if not segments then
        return default
    end
    local e
    for i=1,#segments do
        local s = segments[i]
        if s[1] >= default then
            if s[2] == default then
                return default
            else
                e = i
                break
            end
        end
    end
    if e then
        local b = segments[e-1]
        local e = segments[e]
        return b[2] + (e[2] - b[2]) * (default - b[1]) / (e[1] - b[1])
    else
        return false
    end
end

local function getfactors(data,instancespec)
    if instancespec == true then
        -- take default
    elseif type(instancespec) ~= "string" or instancespec == "" then
        return
    end
    local variabledata = data.variabledata
    if not variabledata then
        return
    end
    local instances = variabledata.instances
    local axis      = variabledata.axis
    local segments  = variabledata.segments
    if instances and axis then
        local values
        if instancespec == true then
            -- first instance:
         -- values = instances[1].values
            -- axis defaults:
            values = { }
            for i=1,#axis do
                values[i] = {
                 -- axis  = axis[i].tag,
                    value = axis[i].default,
                }
            end

        else
            for i=1,#instances do
                local instance = instances[i]
                if cleanname(instance.subfamily) == instancespec then
                    values = instance.values
                    break
                end
            end
        end
        if values then
            local factors = { }
            for i=1,#axis do
                local a = axis[i]
                factors[i] = getaxisscale(segments,a.minimum,a.default,a.maximum,values[i].value)
            end
            return factors
        end
        local values = axistofactors(hash[instancespec] or instancespec)
        if values then
            local factors = { }
            for i=1,#axis do
                local a = axis[i]
                local d = a.default
                factors[i] = getaxisscale(segments,a.minimum,d,a.maximum,values[a.name or a.tag] or d)
            end
            return factors
        end
    end
end

local function getscales(regions,factors)
    local scales = { }
    for i=1,#regions do
        local region = regions[i]
        local s = 1
        for j=1,#region do
            local axis  = region[j]
            local f     = factors[j]
            local start = axis.start
            local peak  = axis.peak
            local stop  = axis.stop
            -- get rid of these tests, false flag
            if start > peak or peak > stop then
                -- * 1
            elseif start < 0 and stop > 0 and peak ~= 0 then
                -- * 1
            elseif peak == 0 then
                -- * 1
            elseif f < start or f > stop then
                -- * 0
                s = 0
                break
            elseif f < peak then
             -- s = - s * (f - start) / (peak - start)
                s = s * (f - start) / (peak - start)
            elseif f > peak then
                s = s * (stop - f) / (stop - peak)
            else
                -- * 1
            end
        end
        scales[i] = s
    end
    return scales
end

helpers.getaxisscale  = getaxisscale
helpers.getfactors    = getfactors
helpers.getscales     = getscales
helpers.axistofactors = axistofactors

local function readvariationdata(f,storeoffset,factors) -- store
    local position = getposition(f)
    setposition(f,storeoffset)
    -- header
    local format       = readushort(f)
    local regionoffset = storeoffset + readulong(f)
    local nofdeltadata = readushort(f)
    local deltadata    = { }
    for i=1,nofdeltadata do
        deltadata[i] = readulong(f)
    end
    -- regions
    setposition(f,regionoffset)
    local nofaxis    = readushort(f)
    local nofregions = readushort(f)
    local regions    = { }
    for i=1,nofregions do -- 0
        local t = { }
        for i=1,nofaxis do
            t[i] = { -- maybe no keys, just 1..3
                start = read2dot14(f),
                peak  = read2dot14(f),
                stop  = read2dot14(f),
            }
        end
        regions[i] = t
    end
    -- deltas
    if factors then
        for i=1,nofdeltadata do
            setposition(f,storeoffset+deltadata[i])
            local nofdeltasets = readushort(f)
            local nofshorts    = readushort(f)
            local nofregions   = readushort(f)
            local usedregions  = { }
            local deltas       = { }
            for i=1,nofregions do
                usedregions[i] = regions[readushort(f)+1]
            end
            -- we could test before and save a for
            for i=1,nofdeltasets do
                local t = { } -- newtable
                for i=1,nofshorts do
                    t[i] = readshort(f)
                end
                for i=nofshorts+1,nofregions do
                    t[i] = readinteger(f)
                end
                deltas[i] = t
            end
            deltadata[i] = {
                regions = usedregions,
                deltas  = deltas,
                scales  = factors and getscales(usedregions,factors) or nil,
            }
        end
    end
    setposition(f,position)
    return regions, deltadata
end

helpers.readvariationdata = readvariationdata

-- Beware: only use the simple variant if we don't set keys/values (otherwise too many entries). We
-- could also have a variant that applies a function but there is no real benefit in this.

local function readcoverage(f,offset,simple)
    setposition(f,offset)
    local coverageformat = readushort(f)
    local coverage = { }
    if coverageformat == 1 then
        local nofcoverage = readushort(f)
        if simple then
            for i=1,nofcoverage do
                coverage[i] = readushort(f)
            end
        else
            for i=0,nofcoverage-1 do
                coverage[readushort(f)] = i -- index in record
            end
        end
    elseif coverageformat == 2 then
        local nofranges = readushort(f)
        local n = simple and 1 or 0 -- needs checking
        for i=1,nofranges do
            local firstindex = readushort(f)
            local lastindex  = readushort(f)
            local coverindex = readushort(f)
            if simple then
                for i=firstindex,lastindex do
                    coverage[n] = i
                    n = n + 1
                end
            else
                for i=firstindex,lastindex do
                    coverage[i] = n
                    n = n + 1
                end
            end
        end
    else
        report("unknown coverage format %a ",coverageformat)
    end
    return coverage
end

local function readclassdef(f,offset,preset)
    setposition(f,offset)
    local classdefformat = readushort(f)
    local classdef = { }
    if type(preset) == "number" then
        for k=0,preset-1 do
            classdef[k] = 1
        end
    end
    if classdefformat == 1 then
        local index       = readushort(f)
        local nofclassdef = readushort(f)
        for i=1,nofclassdef do
            classdef[index] = readushort(f) + 1
            index = index + 1
        end
    elseif classdefformat == 2 then
        local nofranges = readushort(f)
        local n = 0
        for i=1,nofranges do
            local firstindex = readushort(f)
            local lastindex  = readushort(f)
            local class      = readushort(f) + 1
            for i=firstindex,lastindex do
                classdef[i] = class
            end
        end
    else
        report("unknown classdef format %a ",classdefformat)
    end
    if type(preset) == "table" then
        for k in next, preset do
            if not classdef[k] then
                classdef[k] = 1
            end
        end
    end
    return classdef
end

local function classtocoverage(defs)
    if defs then
        local list = { }
        for index, class in next, defs do
            local c = list[class]
            if c then
                c[#c+1] = index
            else
                list[class] = { index }
            end
        end
        return list
    end
end

-- extra readers

local skips = { [0] =
    0, -- ----
    1, -- ---x
    1, -- --y-
    2, -- --yx
    1, -- -h--
    2, -- -h-x
    2, -- -hy-
    3, -- -hyx
    2, -- v--x
    2, -- v-y-
    3, -- v-yx
    2, -- vh--
    3, -- vh-x
    3, -- vhy-
    4, -- vhyx
}

-- We can assume that 0 is nothing and in fact we can start at 1 as
-- usual in Lua to make sure of that.

local function readvariation(f,offset)
    local p = getposition(f)
    setposition(f,offset)
    local outer  = readushort(f)
    local inner  = readushort(f)
    local format = readushort(f)
    setposition(f,p)
    if format == 0x8000 then
        return outer, inner
    end
end

local function readposition(f,format,mainoffset,getdelta)
    if format == 0 then
        return
    end
    -- a few happen often
    if format == 0x04 then
        local h = readshort(f)
        if h == 0 then
            return
        else
            return { 0, 0, h, 0 }
        end
    end
    if format == 0x05 then
        local x = readshort(f)
        local h = readshort(f)
        if x == 0 and h == 0 then
            return
        else
            return { x, 0, h, 0 }
        end
    end
    if format == 0x44 then
        local h = readshort(f)
        if getdelta then
            local d = readshort(f) -- short or ushort
            if d > 0 then
                local outer, inner = readvariation(f,mainoffset+d)
                if outer then
                    h = h + getdelta(outer,inner)
                end
            end
        else
            skipshort(f,1)
        end
        if h == 0 then
            return
        else
            return { 0, 0, h, 0 }
        end
    end
    --
    -- todo:
    --
    -- if format == 0x55 then
    --     local x = readshort(f)
    --     local h = readshort(f)
    --     ....
    -- end
    --
    local x = bittest(format,0x01) and readshort(f) or 0 -- x placement
    local y = bittest(format,0x02) and readshort(f) or 0 -- y placement
    local h = bittest(format,0x04) and readshort(f) or 0 -- h advance
    local v = bittest(format,0x08) and readshort(f) or 0 -- v advance
    if format >= 0x10 then
        local X = bittest(format,0x10) and skipshort(f) or 0
        local Y = bittest(format,0x20) and skipshort(f) or 0
        local H = bittest(format,0x40) and skipshort(f) or 0
        local V = bittest(format,0x80) and skipshort(f) or 0
        local s = skips[extract(format,4,4)]
        if s > 0 then
            skipshort(f,s)
        end
        if getdelta then
            if X > 0 then
                local outer, inner = readvariation(f,mainoffset+X)
                if outer then
                    x = x + getdelta(outer,inner)
                end
            end
            if Y > 0 then
                local outer, inner = readvariation(f,mainoffset+Y)
                if outer then
                    y = y + getdelta(outer,inner)
                end
            end
            if H > 0 then
                local outer, inner = readvariation(f,mainoffset+H)
                if outer then
                    h = h + getdelta(outer,inner)
                end
            end
            if V > 0 then
                local outer, inner = readvariation(f,mainoffset+V)
                if outer then
                    v = v + getdelta(outer,inner)
                end
            end
        end
        return { x, y, h, v }
    elseif x == 0 and y == 0 and h == 0 and v == 0 then
        return
    else
        return { x, y, h, v }
    end
end

local function readanchor(f,offset,getdelta) -- maybe also ignore 0's as in pos
    if not offset or offset == 0 then
        return nil -- false
    end
    setposition(f,offset)
    -- no need to skip as we position each
    local format = readshort(f) -- 1: x y 2: x y index 3 x y X Y
    local x = readshort(f)
    local y = readshort(f)
    if format == 3 then
        if getdelta then
            local X = readshort(f)
            local Y = readshort(f)
            if X > 0 then
                local outer, inner = readvariation(f,offset+X)
                if outer then
                    x = x + getdelta(outer,inner)
                end
            end
            if Y > 0 then
                local outer, inner = readvariation(f,offset+Y)
                if outer then
                    y = y + getdelta(outer,inner)
                end
            end
        else
            skipshort(f,2)
        end
        return { x, y } -- , { xindex, yindex }
    else
        return { x, y }
    end
end

-- common handlers: inlining can be faster but we cache anyway
-- so we don't bother too much about speed here

local function readfirst(f,offset)
    if offset then
        setposition(f,offset)
    end
    return { readushort(f) }
end

local function readarray(f,offset,first)
    if offset then
        setposition(f,offset)
    end
    local n = readushort(f)
    if first then
        local t = { first }
        for i=2,n do
            t[i] = readushort(f)
        end
        return t, n
    elseif n > 0 then
        local t = { }
        for i=1,n do
            t[i] = readushort(f)
        end
        return t, n
    end
end

local function readcoveragearray(f,offset,t,simple)
    if not t then
        return nil
    end
    local n = #t
    if n == 0 then
        return nil
    end
    for i=1,n do
        t[i] = readcoverage(f,offset+t[i],simple)
    end
    return t
end

local function covered(subset,all)
    local used, u
    for i=1,#subset do
        local s = subset[i]
        if all[s] then
            if used then
                u = u + 1
                used[u] = s
            else
                u = 1
                used = { s }
            end
        end
    end
    return used
end

-- We generalize the chained lookups so that we can do with only one handler
-- when processing them.

-- pruned

local function readlookuparray(f,noflookups,nofcurrent)
    local lookups = { }
    if noflookups > 0 then
        local length = 0
        for i=1,noflookups do
            local index = readushort(f) + 1
            if index > length then
                length = index
            end
            local lookup = readushort(f) + 1
            local list   = lookups[index]
            if list then
                list[#list+1] = lookup
            else
                lookups[index] = { lookup }
            end
        end
        for index=1,length do
            if not lookups[index] then
                lookups[index] = false
            end
        end
     -- if length > nofcurrent then
     --     report("more lookups than currently matched characters")
     -- end
    end
    return lookups
end

-- not pruned
--
-- local function readlookuparray(f,noflookups,nofcurrent)
--     local lookups = { }
--     for i=1,nofcurrent do
--         lookups[i] = false
--     end
--     for i=1,noflookups do
--         local index = readushort(f) + 1
--         if index > nofcurrent then
--             report("more lookups than currently matched characters")
--             for i=nofcurrent+1,index-1 do
--                 lookups[i] = false
--             end
--             nofcurrent = index
--         end
--         lookups[index] = readushort(f) + 1
--     end
--     return lookups
-- end

local function unchainedcontext(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs,what)
    local tableoffset = lookupoffset + offset
    setposition(f,tableoffset)
    local subtype = readushort(f)
    if subtype == 1 then
        local coverage     = readushort(f)
        local subclasssets = readarray(f)
        local rules        = { }
        if subclasssets then
            coverage = readcoverage(f,tableoffset+coverage,true)
            for i=1,#subclasssets do
                local offset = subclasssets[i]
                if offset > 0 then
                    local firstcoverage = coverage[i]
                    local rulesoffset   = tableoffset + offset
                    local subclassrules = readarray(f,rulesoffset)
                    for rule=1,#subclassrules do
                        setposition(f,rulesoffset + subclassrules[rule])
                        local nofcurrent = readushort(f)
                        local noflookups = readushort(f)
                        local current    = { { firstcoverage } }
                        for i=2,nofcurrent do
                            current[i] = { readushort(f) }
                        end
                        local lookups = readlookuparray(f,noflookups,nofcurrent)
                        rules[#rules+1] = {
                            current = current,
                            lookups = lookups
                        }
                    end
                end
            end
        else
            report("empty subclassset in %a subtype %i","unchainedcontext",subtype)
        end
        return {
            format = "glyphs",
            rules  = rules,
        }
    elseif subtype == 2 then
        -- We expand the classes as later on we do a pack over the whole table so then we get
        -- back efficiency. This way we can also apply the coverage to the first current.
        local coverage        = readushort(f)
        local currentclassdef = readushort(f)
        local subclasssets    = readarray(f)
        local rules           = { }
        if subclasssets then
            coverage             = readcoverage(f,tableoffset + coverage)
            currentclassdef      = readclassdef(f,tableoffset + currentclassdef,coverage)
            local currentclasses = classtocoverage(currentclassdef,fontdata.glyphs)
            for class=1,#subclasssets do
                local offset = subclasssets[class]
                if offset > 0 then
                    local firstcoverage = currentclasses[class]
                    if firstcoverage then
                        firstcoverage = covered(firstcoverage,coverage) -- bonus
                        if firstcoverage then
                            local rulesoffset   = tableoffset + offset
                            local subclassrules = readarray(f,rulesoffset)
                            for rule=1,#subclassrules do
                                setposition(f,rulesoffset + subclassrules[rule])
                                local nofcurrent = readushort(f)
                                local noflookups = readushort(f)
                                local current    = { firstcoverage }
                                for i=2,nofcurrent do
                                    current[i] = currentclasses[readushort(f) + 1]
                                end
                                local lookups = readlookuparray(f,noflookups,nofcurrent)
                                rules[#rules+1] = {
                                    current = current,
                                    lookups = lookups
                                }
                            end
                        else
                            report("no coverage")
                        end
                    else
                        report("no coverage class")
                    end
                end
            end
        else
            report("empty subclassset in %a subtype %i","unchainedcontext",subtype)
        end
        return {
            format = "class",
            rules  = rules,
        }
    elseif subtype == 3 then
        local current    = readarray(f)
        local noflookups = readushort(f)
        local lookups    = readlookuparray(f,noflookups,#current)
        current = readcoveragearray(f,tableoffset,current,true)
        return {
            format = "coverage",
            rules  = {
                {
                    current = current,
                    lookups = lookups,
                }
            }
        }
    else
        report("unsupported subtype %a in %a %s",subtype,"unchainedcontext",what)
    end
end

-- todo: optimize for n=1 ?

-- class index needs checking, probably no need for +1

local function chainedcontext(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs,what)
    local tableoffset = lookupoffset + offset
    setposition(f,tableoffset)
    local subtype = readushort(f)
    if subtype == 1 then
        local coverage     = readushort(f)
        local subclasssets = readarray(f)
        local rules        = { }
        if subclasssets then
            coverage = readcoverage(f,tableoffset+coverage,true)
            for i=1,#subclasssets do
                local offset = subclasssets[i]
                if offset > 0 then
                    local firstcoverage = coverage[i]
                    local rulesoffset   = tableoffset + offset
                    local subclassrules = readarray(f,rulesoffset)
                    for rule=1,#subclassrules do
                        setposition(f,rulesoffset + subclassrules[rule])
                        local nofbefore = readushort(f)
                        local before
                        if nofbefore > 0 then
                            before = { }
                            for i=1,nofbefore do
                                before[i] = { readushort(f) }
                            end
                        end
                        local nofcurrent = readushort(f)
                        local current    = { { firstcoverage } }
                        for i=2,nofcurrent do
                            current[i] = { readushort(f) }
                        end
                        local nofafter = readushort(f)
                        local after
                        if nofafter > 0 then
                            after = { }
                            for i=1,nofafter do
                                after[i] = { readushort(f) }
                            end
                        end
                        local noflookups = readushort(f)
                        local lookups    = readlookuparray(f,noflookups,nofcurrent)
                        rules[#rules+1] = {
                            before  = before,
                            current = current,
                            after   = after,
                            lookups = lookups,
                        }
                    end
                end
            end
        else
            report("empty subclassset in %a subtype %i","chainedcontext",subtype)
        end
        return {
            format = "glyphs",
            rules  = rules,
        }
    elseif subtype == 2 then
        local coverage        = readushort(f)
        local beforeclassdef  = readushort(f)
        local currentclassdef = readushort(f)
        local afterclassdef   = readushort(f)
        local subclasssets    = readarray(f)
        local rules           = { }
        if subclasssets then
            local coverage        = readcoverage(f,tableoffset + coverage)
            local beforeclassdef  = readclassdef(f,tableoffset + beforeclassdef,nofglyphs)
            local currentclassdef = readclassdef(f,tableoffset + currentclassdef,coverage)
            local afterclassdef   = readclassdef(f,tableoffset + afterclassdef,nofglyphs)
            local beforeclasses   = classtocoverage(beforeclassdef,fontdata.glyphs)
            local currentclasses  = classtocoverage(currentclassdef,fontdata.glyphs)
            local afterclasses    = classtocoverage(afterclassdef,fontdata.glyphs)
            for class=1,#subclasssets do
                local offset = subclasssets[class]
                if offset > 0 then
                    local firstcoverage = currentclasses[class]
                    if firstcoverage then
                        firstcoverage = covered(firstcoverage,coverage) -- bonus
                        if firstcoverage then
                            local rulesoffset   = tableoffset + offset
                            local subclassrules = readarray(f,rulesoffset)
                            for rule=1,#subclassrules do
                                -- watch out, in context we first get the counts and then the arrays while
                                -- here we get them mixed
                                setposition(f,rulesoffset + subclassrules[rule])
                                local nofbefore = readushort(f)
                                local before
                                if nofbefore > 0 then
                                    before = { }
                                    for i=1,nofbefore do
                                        before[i] = beforeclasses[readushort(f) + 1]
                                    end
                                end
                                local nofcurrent = readushort(f)
                                local current    = { firstcoverage }
                                for i=2,nofcurrent do
                                    current[i] = currentclasses[readushort(f)+ 1]
                                end
                                local nofafter = readushort(f)
                                local after
                                if nofafter > 0 then
                                    after = { }
                                    for i=1,nofafter do
                                        after[i] = afterclasses[readushort(f) + 1]
                                    end
                                end
                                -- no sequence index here (so why in context as it saves nothing)
                                local noflookups = readushort(f)
                                local lookups    = readlookuparray(f,noflookups,nofcurrent)
                                rules[#rules+1] = {
                                    before  = before,
                                    current = current,
                                    after   = after,
                                    lookups = lookups,
                                }
                            end
                        else
                            report("no coverage")
                        end
                    else
                        report("class is not covered")
                    end
                end
            end
        else
            report("empty subclassset in %a subtype %i","chainedcontext",subtype)
        end
        return {
            format = "class",
            rules  = rules,
        }
    elseif subtype == 3 then
        local before     = readarray(f)
        local current    = readarray(f)
        local after      = readarray(f)
        local noflookups = readushort(f)
        local lookups    = readlookuparray(f,noflookups,#current)
        before  = readcoveragearray(f,tableoffset,before,true)
        current = readcoveragearray(f,tableoffset,current,true)
        after   = readcoveragearray(f,tableoffset,after,true)
        return {
            format = "coverage",
            rules  = {
                {
                    before  = before,
                    current = current,
                    after   = after,
                    lookups = lookups,
                }
            }
        }
    else
        report("unsupported subtype %a in %a %s",subtype,"chainedcontext",what)
    end
end

local function extension(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs,types,handlers,what)
    local tableoffset = lookupoffset + offset
    setposition(f,tableoffset)
    local subtype = readushort(f)
    if subtype == 1 then
        local lookuptype = types[readushort(f)]
        local faroffset  = readulong(f)
        local handler    = handlers[lookuptype]
        if handler then
            -- maybe we can just pass one offset (or tableoffset first)
            return handler(f,fontdata,lookupid,tableoffset + faroffset,0,glyphs,nofglyphs), lookuptype
        else
            report("no handler for lookuptype %a subtype %a in %s %s",lookuptype,subtype,what,"extension")
        end
    else
        report("unsupported subtype %a in %s %s",subtype,what,"extension")
    end
end

-- gsub handlers

function gsubhandlers.single(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    local tableoffset = lookupoffset + offset
    setposition(f,tableoffset)
    local subtype = readushort(f)
    if subtype == 1 then
        local coverage = readushort(f)
        local delta    = readshort(f) -- can be negative
        local coverage = readcoverage(f,tableoffset+coverage) -- not simple as we need to set key/value anyway
        for index in next, coverage do
            local newindex = index + delta
            if index > nofglyphs or newindex > nofglyphs then
                report("invalid index in %s format %i: %i -> %i (max %i)","single",subtype,index,newindex,nofglyphs)
                coverage[index] = nil
            else
                coverage[index] = newindex
            end
        end
        return {
            coverage = coverage
        }
    elseif subtype == 2 then -- in streamreader a seek and fetch is faster than a temp table
        local coverage        = readushort(f)
        local nofreplacements = readushort(f)
        local replacements    = { }
        for i=1,nofreplacements do
            replacements[i] = readushort(f)
        end
        local coverage = readcoverage(f,tableoffset + coverage) -- not simple as we need to set key/value anyway
        for index, newindex in next, coverage do
            newindex = newindex + 1
            if index > nofglyphs or newindex > nofglyphs then
                report("invalid index in %s format %i: %i -> %i (max %i)","single",subtype,index,newindex,nofglyphs)
                coverage[index] = nil
            else
                coverage[index] = replacements[newindex]
            end
        end
        return {
            coverage = coverage
        }
    else
        report("unsupported subtype %a in %a substitution",subtype,"single")
    end
end

-- we see coverage format 0x300 in some old ms fonts

local function sethandler(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs,what)
    local tableoffset = lookupoffset + offset
    setposition(f,tableoffset)
    local subtype = readushort(f)
    if subtype == 1 then
        local coverage    = readushort(f)
        local nofsequence = readushort(f)
        local sequences   = { }
        for i=1,nofsequence do
            sequences[i] = readushort(f)
        end
        for i=1,nofsequence do
            setposition(f,tableoffset + sequences[i])
            local n = readushort(f)
            local s = { }
            for i=1,n do
                s[i] = readushort(f)
            end
            sequences[i] = s
        end
        local coverage = readcoverage(f,tableoffset + coverage)
        for index, newindex in next, coverage do
            newindex = newindex + 1
            if index > nofglyphs or newindex > nofglyphs then
                report("invalid index in %s format %i: %i -> %i (max %i)",what,subtype,index,newindex,nofglyphs)
                coverage[index] = nil
            else
                coverage[index] = sequences[newindex]
            end
        end
        return {
            coverage = coverage
        }
    else
        report("unsupported subtype %a in %a substitution",subtype,what)
    end
end

function gsubhandlers.multiple(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    return sethandler(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs,"multiple")
end

function gsubhandlers.alternate(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    return sethandler(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs,"alternate")
end

function gsubhandlers.ligature(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    local tableoffset = lookupoffset + offset
    setposition(f,tableoffset)
    local subtype = readushort(f)
    if subtype == 1 then
        local coverage  = readushort(f)
        local nofsets   = readushort(f)
        local ligatures = { }
        for i=1,nofsets do
            ligatures[i] = readushort(f)
        end
        for i=1,nofsets do
            local offset = lookupoffset + offset + ligatures[i]
            setposition(f,offset)
            local n = readushort(f)
            local l = { }
            for i=1,n do
                l[i] = offset + readushort(f)
            end
            ligatures[i] = l
        end
        local coverage = readcoverage(f,tableoffset + coverage)
        for index, newindex in next, coverage do
            local hash = { }
            local ligatures = ligatures[newindex+1]
            for i=1,#ligatures do
                local offset = ligatures[i]
                setposition(f,offset)
                local lig = readushort(f)
                local cnt = readushort(f)
                local hsh = hash
                for i=2,cnt do
                    local c = readushort(f)
                    local h = hsh[c]
                    if not h then
                        h = { }
                        hsh[c] = h
                    end
                    hsh =  h
                end
                hsh.ligature = lig
            end
            coverage[index] = hash
        end
        return {
            coverage = coverage
        }
    else
        report("unsupported subtype %a in %a substitution",subtype,"ligature")
    end
end

function gsubhandlers.context(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    return unchainedcontext(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs,"substitution"), "context"
end

function gsubhandlers.chainedcontext(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    return chainedcontext(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs,"substitution"), "chainedcontext"
end

function gsubhandlers.extension(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    return extension(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs,gsubtypes,gsubhandlers,"substitution")
end

function gsubhandlers.reversechainedcontextsingle(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    local tableoffset = lookupoffset + offset
    setposition(f,tableoffset)
    local subtype = readushort(f)
    if subtype == 1 then -- NEEDS CHECKING
        local current      = readfirst(f)
        local before       = readarray(f)
        local after        = readarray(f)
        local replacements = readarray(f)
        current = readcoveragearray(f,tableoffset,current,true)
        before  = readcoveragearray(f,tableoffset,before,true)
        after   = readcoveragearray(f,tableoffset,after,true)
        return {
            coverage = {
                format       = "reversecoverage", -- reversesub
                before       = before,
                current      = current,
                after        = after,
                replacements = replacements,
            }
        }, "reversechainedcontextsingle"
    else
        report("unsupported subtype %a in %a substitution",subtype,"reversechainedcontextsingle")
    end
end

-- gpos handlers

local function readpairsets(f,tableoffset,sets,format1,format2,mainoffset,getdelta)
    local done = { }
    for i=1,#sets do
        local offset = sets[i]
        local reused = done[offset]
        if not reused then
            offset = tableoffset + offset
            setposition(f,offset)
            local n = readushort(f)
            reused = { }
            for i=1,n do
                reused[i] = {
                    readushort(f), -- second glyph id
                    readposition(f,format1,offset,getdelta),
                    readposition(f,format2,offset,getdelta),
                }
            end
            done[offset] = reused
        end
        sets[i] = reused
    end
    return sets
end

local function readpairclasssets(f,nofclasses1,nofclasses2,format1,format2,mainoffset,getdelta)
    local classlist1  = { }
    for i=1,nofclasses1 do
        local classlist2 = { }
        classlist1[i] = classlist2
        for j=1,nofclasses2 do
            local one = readposition(f,format1,mainoffset,getdelta)
            local two = readposition(f,format2,mainoffset,getdelta)
            if one or two then
                classlist2[j] = { one, two }
            else
                classlist2[j] = false
            end
        end
    end
    return classlist1
end

-- no real gain in kerns as we pack

function gposhandlers.single(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    local tableoffset = lookupoffset + offset
    setposition(f,tableoffset)
    local subtype  = readushort(f)
    local getdelta = fontdata.temporary.getdelta
    if subtype == 1 then
        local coverage = readushort(f)
        local format   = readushort(f)
        local value    = readposition(f,format,tableoffset,getdelta)
        local coverage = readcoverage(f,tableoffset+coverage)
        for index, newindex in next, coverage do
            coverage[index] = value
        end
        return {
            format   = "pair",
            coverage = coverage,
        }
    elseif subtype == 2 then
        local coverage  = readushort(f)
        local format    = readushort(f)
        local nofvalues = readushort(f)
        local values    = { }
        for i=1,nofvalues do
            values[i] = readposition(f,format,tableoffset,getdelta)
        end
        local coverage = readcoverage(f,tableoffset+coverage)
        for index, newindex in next, coverage do
            coverage[index] = values[newindex+1]
        end
        return {
            format   = "pair",
            coverage = coverage,
        }
    else
        report("unsupported subtype %a in %a positioning",subtype,"single")
    end
end

-- this needs checking! if no second pair then another advance over the list

-- ValueFormat1 applies to the ValueRecord of the first glyph in each pair. ValueRecords for all first glyphs must use ValueFormat1. If ValueFormat1 is set to zero (0), the corresponding glyph has no ValueRecord and, therefore, should not be repositioned.
-- ValueFormat2 applies to the ValueRecord of the second glyph in each pair. ValueRecords for all second glyphs must use ValueFormat2. If ValueFormat2 is set to null, then the second glyph of the pair is the “next” glyph for which a lookup should be performed.

-- !!!!! this needs checking: when both false, we have no hit so then we might need to fall through

function gposhandlers.pair(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    local tableoffset = lookupoffset + offset
    setposition(f,tableoffset)
    local subtype  = readushort(f)
    local getdelta = fontdata.temporary.getdelta
    if subtype == 1 then
        local coverage = readushort(f)
        local format1  = readushort(f)
        local format2  = readushort(f)
        local sets     = readarray(f)
              sets     = readpairsets(f,tableoffset,sets,format1,format2,mainoffset,getdelta)
              coverage = readcoverage(f,tableoffset + coverage)
        for index, newindex in next, coverage do
            local set  = sets[newindex+1]
            local hash = { }
            for i=1,#set do
                local value = set[i]
                if value then
                    local other  = value[1]
                    local first  = value[2]
                    local second = value[3]
                    if first or second then
                        hash[other] = { first, second } -- needs checking
                    else
                        hash[other] = nil
                    end
                end
            end
            coverage[index] = hash
        end
        return {
            format   = "pair",
            coverage = coverage,
        }
    elseif subtype == 2 then
        local coverage     = readushort(f)
        local format1      = readushort(f)
        local format2      = readushort(f)
        local classdef1    = readushort(f)
        local classdef2    = readushort(f)
        local nofclasses1  = readushort(f) -- incl class 0
        local nofclasses2  = readushort(f) -- incl class 0
        local classlist    = readpairclasssets(f,nofclasses1,nofclasses2,format1,format2,tableoffset,getdelta)
              coverage     = readcoverage(f,tableoffset+coverage)
              classdef1    = readclassdef(f,tableoffset+classdef1,coverage)
              classdef2    = readclassdef(f,tableoffset+classdef2,nofglyphs)
        local usedcoverage = { }
        for g1, c1 in next, classdef1 do
            if coverage[g1] then
                local l1 = classlist[c1]
                if l1 then
                    local hash = { }
                    for paired, class in next, classdef2 do
                        local offsets = l1[class]
                        if offsets then
                            local first  = offsets[1]
                            local second = offsets[2]
                            if first or second then
                                hash[paired] = { first, second }
                            else
                                -- upto the next lookup for this combination
                            end
                        end
                    end
                    usedcoverage[g1] = hash
                end
            end
        end
        return {
            format   = "pair",
            coverage = usedcoverage,
        }
    elseif subtype == 3 then
        report("yet unsupported subtype %a in %a positioning",subtype,"pair")
    else
        report("unsupported subtype %a in %a positioning",subtype,"pair")
    end
end

function gposhandlers.cursive(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    local tableoffset = lookupoffset + offset
    setposition(f,tableoffset)
    local subtype  = readushort(f)
    local getdelta = fontdata.temporary.getdelta
    if subtype == 1 then
        local coverage   = tableoffset + readushort(f)
        local nofrecords = readushort(f)
        local records    = { }
        for i=1,nofrecords do
            local entry = readushort(f)
            local exit  = readushort(f)
            records[i] = {
                entry = entry ~= 0 and (tableoffset + entry) or false,
                exit  = exit  ~= 0 and (tableoffset + exit ) or false,
            }
        end
        coverage = readcoverage(f,coverage)
        for i=1,nofrecords do
            local r = records[i]
            -- slot 1 will become hash after loading (must be unique per lookup when packed)
            records[i] = {
                1,
                readanchor(f,r.entry,getdelta) or nil,
                readanchor(f,r.exit, getdelta) or nil,
            }
        end
        for index, newindex in next, coverage do
            coverage[index] = records[newindex+1]
        end
        return {
            coverage = coverage,
        }
    else
        report("unsupported subtype %a in %a positioning",subtype,"cursive")
    end
end

local function handlemark(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs,ligature)
    local tableoffset = lookupoffset + offset
    setposition(f,tableoffset)
    local subtype  = readushort(f)
    local getdelta = fontdata.temporary.getdelta
    if subtype == 1 then
        -- we are one based, not zero
        local markcoverage = tableoffset + readushort(f)
        local basecoverage = tableoffset + readushort(f)
        local nofclasses   = readushort(f)
        local markoffset   = tableoffset + readushort(f)
        local baseoffset   = tableoffset + readushort(f)
        --
        local markcoverage = readcoverage(f,markcoverage)
        local basecoverage = readcoverage(f,basecoverage,true) -- TO BE CHECKED: true
        --
        setposition(f,markoffset)
        local markclasses    = { }
        local nofmarkclasses = readushort(f)
        --
        local lastanchor  = fontdata.lastanchor or 0
        local usedanchors = { }
        --
        for i=1,nofmarkclasses do
            local class  = readushort(f) + 1
            local offset = readushort(f)
            if offset == 0 then
                markclasses[i] = false
            else
                markclasses[i] = { class, markoffset + offset }
            end
            usedanchors[class] = true
        end
        for i=1,nofmarkclasses do
            local mc = markclasses[i]
            if mc then
                mc[2] = readanchor(f,mc[2],getdelta)
            end
        end
        --
        setposition(f,baseoffset)
        local nofbaserecords = readushort(f)
        local baserecords    = { }
        --
        if ligature then
            -- 3 components
            -- 1 : class .. nofclasses -- NULL when empty
            -- 2 : class .. nofclasses -- NULL when empty
            -- 3 : class .. nofclasses -- NULL when empty
            for i=1,nofbaserecords do -- here i is the class
                local offset = readushort(f)
                if offset == 0 then
                    baserecords[i] = false
                else
                    baserecords[i] = baseoffset + offset
                end
            end
            for i=1,nofbaserecords do
                local recordoffset = baserecords[i]
                if recordoffset then
                    setposition(f,recordoffset)
                    local nofcomponents = readushort(f)
                    local components = { }
                    for i=1,nofcomponents do
                        local classes = { }
                        for i=1,nofclasses do
                            local offset = readushort(f)
                            if offset ~= 0 then
                                classes[i] = recordoffset + offset
                            else
                                classes[i] = false
                            end
                        end
                        components[i] = classes
                    end
                    baserecords[i] = components
                end
            end
            local baseclasses = { } -- setmetatableindex("table")
            for i=1,nofclasses do
                baseclasses[i] = { }
            end
            for i=1,nofbaserecords do
                local components = baserecords[i]
                if components then
                    local b = basecoverage[i]
                    for c=1,#components do
                        local classes = components[c]
                        if classes then
                            for i=1,nofclasses do
                                local anchor = readanchor(f,classes[i],getdelta)
                                local bclass = baseclasses[i]
                                local bentry = bclass[b]
                                if bentry then
                                    bentry[c] = anchor
                                else
                                    bclass[b]= { [c] = anchor }
                                end
                            end
                        end
                    end
                end
            end
            for index, newindex in next, markcoverage do
                markcoverage[index] = markclasses[newindex+1] or nil
            end
            return {
                format      = "ligature",
                baseclasses = baseclasses,
                coverage    = markcoverage,
            }
        else
            for i=1,nofbaserecords do
                local r = { }
                for j=1,nofclasses do
                    local offset = readushort(f)
                    if offset == 0 then
                        r[j] = false
                    else
                        r[j] = baseoffset + offset
                    end
                end
                baserecords[i] = r
            end
            local baseclasses = { } -- setmetatableindex("table")
            for i=1,nofclasses do
                baseclasses[i] = { }
            end
            for i=1,nofbaserecords do
                local r = baserecords[i]
                local b = basecoverage[i]
                for j=1,nofclasses do
                    baseclasses[j][b] = readanchor(f,r[j],getdelta)
                end
            end
            for index, newindex in next, markcoverage do
                markcoverage[index] = markclasses[newindex+1] or nil
            end
            -- we could actually already calculate the displacement if we want
            return {
                format      = "base",
                baseclasses = baseclasses,
                coverage    = markcoverage,
            }
        end
    else
        report("unsupported subtype %a in",subtype)
    end

end

function gposhandlers.marktobase(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    return handlemark(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
end

function gposhandlers.marktoligature(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    return handlemark(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs,true)
end

function gposhandlers.marktomark(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    return handlemark(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
end

function gposhandlers.context(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    return unchainedcontext(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs,"positioning"), "context"
end

function gposhandlers.chainedcontext(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    return chainedcontext(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs,"positioning"), "chainedcontext"
end

function gposhandlers.extension(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs)
    return extension(f,fontdata,lookupid,lookupoffset,offset,glyphs,nofglyphs,gpostypes,gposhandlers,"positioning")
end

-- main loader

do

    local plugins = { }

    function plugins.size(f,fontdata,tableoffset,feature)
        if fontdata.designsize then
            -- yes, there are fonts with multiple size entries ... it probably relates
            -- to the other two fields (menu entries in some language)
        else
            local function check(offset)
                setposition(f,offset)
                local designsize = readushort(f)
                if designsize > 0 then -- we could also have a threshold
                    local fontstyleid = readushort(f)
                    local guimenuid   = readushort(f)
                    local minsize     = readushort(f)
                    local maxsize     = readushort(f)
                    if minsize == 0 and maxsize == 0 and fontstyleid == 0 and guimenuid == 0 then
                        minsize = designsize
                        maxsize = designsize
                    end
                    if designsize >= minsize and designsize <= maxsize then
                        return minsize, maxsize, designsize
                    end
                end
            end
            local minsize, maxsize, designsize = check(tableoffset+feature.offset+feature.parameters)
            if not designsize then
                -- some old adobe fonts have: tableoffset+feature.parameters and we could
                -- use some heuristic but why bother ... this extra check will be removed
                -- some day and/or when we run into an issue
                minsize, maxsize, designsize = check(tableoffset+feature.parameters)
                if designsize then
                    report("bad size feature in %a, falling back to wrong offset",fontdata.filename or "?")
                else
                    report("bad size feature in %a,",fontdata.filename or "?")
                end
            end
            if designsize then
                fontdata.minsize    = minsize
                fontdata.maxsize    = maxsize
                fontdata.designsize = designsize
            end
        end
    end

 -- function plugins.rvrn(f,fontdata,tableoffset,feature)
 --     -- todo, at least a message
 -- end

    -- feature order needs checking ... as we loop over a hash ... however, in the file
    -- they are sorted so order is not that relevant

    local function reorderfeatures(fontdata,scripts,features)
        local scriptlangs  = { }
        local featurehash  = { }
        local featureorder = { }
        for script, languages in next, scripts do
            for language, record in next, languages do
                local hash = { }
                local list = record.featureindices
                for k=1,#list do
                    local index   = list[k]
                    local feature = features[index]
                    local lookups = feature.lookups
                    local tag     = feature.tag
                    if tag then
                        hash[tag] = true
                    end
                    if lookups then
                        for i=1,#lookups do
                            local lookup = lookups[i]
                            local o = featureorder[lookup]
                            if o then
                                local okay = true
                                for i=1,#o do
                                    if o[i] == tag then
                                        okay = false
                                        break
                                    end
                                end
                                if okay then
                                    o[#o+1] = tag
                                end
                            else
                                featureorder[lookup] = { tag }
                            end
                            local f = featurehash[lookup]
                            if f then
                                local h = f[tag]
                                if h then
                                    local s = h[script]
                                    if s then
                                        s[language] = true
                                    else
                                        h[script] = { [language] = true }
                                    end
                                else
                                    f[tag] = { [script] = { [language] = true } }
                                end
                            else
                                featurehash[lookup] = { [tag] = { [script] = { [language] = true } } }
                            end
                            --
                            local h = scriptlangs[tag]
                            if h then
                                local s = h[script]
                                if s then
                                    s[language] = true
                                else
                                    h[script] = { [language] = true }
                                end
                            else
                                scriptlangs[tag] = { [script] = { [language] = true } }
                            end
                        end
                    end
                end
            end
        end
        return scriptlangs, featurehash, featureorder
    end

    local function readscriplan(f,fontdata,scriptoffset)
        setposition(f,scriptoffset)
        local nofscripts = readushort(f)
        local scripts    = { }
        for i=1,nofscripts do
            scripts[readtag(f)] = scriptoffset + readushort(f)
        end
        -- script list -> language system info
        local languagesystems = setmetatableindex("table")
        for script, offset in next, scripts do
            setposition(f,offset)
            local defaultoffset = readushort(f)
            local noflanguages  = readushort(f)
            local languages     = { }
            if defaultoffset > 0 then
                languages.dflt = languagesystems[offset + defaultoffset]
            end
            for i=1,noflanguages do
                local language      = readtag(f)
                local offset        = offset + readushort(f)
                languages[language] = languagesystems[offset]
            end
            scripts[script] = languages
        end
        -- script list -> language system info -> feature list
        for offset, usedfeatures in next, languagesystems do
            if offset > 0 then
                setposition(f,offset)
                local featureindices        = { }
                usedfeatures.featureindices = featureindices
                usedfeatures.lookuporder    = readushort(f) -- reserved, not used (yet)
                usedfeatures.requiredindex  = readushort(f) -- relates to required (can be 0xFFFF)
                local noffeatures           = readushort(f)
                for i=1,noffeatures do
                    featureindices[i] = readushort(f) + 1
                end
            end
        end
        return scripts
    end

    local function readfeatures(f,fontdata,featureoffset)
        setposition(f,featureoffset)
        local features    = { }
        local noffeatures = readushort(f)
        for i=1,noffeatures do
            -- also shared?
            features[i] = {
                tag    = readtag(f),
                offset = readushort(f)
            }
        end
        --
        for i=1,noffeatures do
            local feature = features[i]
            local offset  = featureoffset+feature.offset
            setposition(f,offset)
            local parameters = readushort(f) -- feature.parameters
            local noflookups = readushort(f)
            if noflookups > 0 then
                local lookups   = { }
                feature.lookups = lookups
                for j=1,noflookups do
                    lookups[j] = readushort(f) + 1
                end
            end
            if parameters > 0 then
                feature.parameters = parameters
                local plugin = plugins[feature.tag]
                if plugin then
                    plugin(f,fontdata,featureoffset,feature)
                end
            end
        end
        return features
    end

    local function readlookups(f,lookupoffset,lookuptypes,featurehash,featureorder)
        setposition(f,lookupoffset)
        local lookups    = { }
        local noflookups = readushort(f)
        for i=1,noflookups do
            lookups[i] = readushort(f)
        end
        for lookupid=1,noflookups do
            local offset = lookups[lookupid]
            setposition(f,lookupoffset+offset)
            local subtables    = { }
            local typebits     = readushort(f)
            local flagbits     = readushort(f)
            local lookuptype   = lookuptypes[typebits]
            local lookupflags  = lookupflags[flagbits]
            local nofsubtables = readushort(f)
            for j=1,nofsubtables do
                subtables[j] = offset + readushort(f) -- we can probably put lookupoffset here
            end
            -- which one wins?
            local markclass = bittest(flagbits,0x0010) -- usemarkfilteringset
            if markclass then
                markclass = readushort(f) -- + 1
            end
            local markset = rshift(flagbits,8)
            if markset > 0 then
                markclass = markset -- + 1
            end
            lookups[lookupid] = {
                type      = lookuptype,
             -- chain     = chaindirections[lookuptype] or nil,
                flags     = lookupflags,
                name      = lookupid,
                subtables = subtables,
                markclass = markclass,
                features  = featurehash[lookupid], -- not if extension
                order     = featureorder[lookupid],
            }
        end
        return lookups
    end

    local f_lookupname = formatters["%s_%s_%s"]

    local function resolvelookups(f,lookupoffset,fontdata,lookups,lookuptypes,lookuphandlers,what,tableoffset)

        local sequences      = fontdata.sequences   or { }
        local sublookuplist  = fontdata.sublookups  or { }
        fontdata.sequences   = sequences
        fontdata.sublookups  = sublookuplist
        local nofsublookups  = #sublookuplist
        local nofsequences   = #sequences -- 0
        local lastsublookup  = nofsublookups
        local lastsequence   = nofsequences
        local lookupnames    = lookupnames[what]
        local sublookuphash  = { }
        local sublookupcheck = { }
        local glyphs         = fontdata.glyphs
        local nofglyphs      = fontdata.nofglyphs or #glyphs
        local noflookups     = #lookups
        local lookupprefix   = sub(what,2,2) -- g[s|p][ub|os]
        --
        for lookupid=1,noflookups do
            local lookup     = lookups[lookupid]
            local lookuptype = lookup.type
            local subtables  = lookup.subtables
            local features   = lookup.features
            local handler    = lookuphandlers[lookuptype]
            if handler then
                local nofsubtables = #subtables
                local order        = lookup.order
                local flags        = lookup.flags
                -- this is expected in th efont handler (faster checking)
                if flags[1] then flags[1] = "mark" end
                if flags[2] then flags[2] = "ligature" end
                if flags[3] then flags[3] = "base" end
                --
                local markclass    = lookup.markclass
             -- local chain        = lookup.chain
                if nofsubtables > 0 then
                    local steps     = { }
                    local nofsteps  = 0
                    local oldtype   = nil
                    for s=1,nofsubtables do
                        local step, lt = handler(f,fontdata,lookupid,lookupoffset,subtables[s],glyphs,nofglyphs)
                        if lt then
                            lookuptype = lt
                            if oldtype and lt ~= oldtype then
                                report("messy %s lookup type %a and %a",what,lookuptype,oldtype)
                            end
                            oldtype = lookuptype
                        end
                        if not step then
                            report("unsupported %s lookup type %a",what,lookuptype)
                        else
                            nofsteps = nofsteps + 1
                            steps[nofsteps] = step
                            local rules = step.rules
                            if rules then
                                for i=1,#rules do
                                    local rule    = rules[i]
                                    local before  = rule.before
                                    local current = rule.current
                                    local after   = rule.after
                                    if before then
                                        for i=1,#before do
                                            before[i] = tohash(before[i])
                                        end
                                        -- as with original ctx ff loader
                                        rule.before = reversed(before)
                                    end
                                    if current then
                                        for i=1,#current do
                                            current[i] = tohash(current[i])
                                        end
                                    end
                                    if after then
                                        for i=1,#after do
                                            after[i] = tohash(after[i])
                                        end
                                    end
                                end
                            end
                        end
                    end
                    if nofsteps ~= nofsubtables then
                        report("bogus subtables removed in %s lookup type %a",what,lookuptype)
                    end
                    lookuptype = lookupnames[lookuptype] or lookuptype
                    if features then
                        nofsequences = nofsequences + 1
                     -- report("registering %i as sequence step %i",lookupid,nofsequences)
                        local l = {
                            index     = nofsequences,
                            name      = f_lookupname(lookupprefix,"s",lookupid+lookupidoffset),
                            steps     = steps,
                            nofsteps  = nofsteps,
                            type      = lookuptype,
                            markclass = markclass or nil,
                            flags     = flags,
                         -- chain     = chain,
                            order     = order,
                            features  = features,
                        }
                        sequences[nofsequences] = l
                        lookup.done = l
                    else
                        nofsublookups = nofsublookups + 1
                     -- report("registering %i as sublookup %i",lookupid,nofsublookups)
                        local l = {
                            index     = nofsublookups,
                            name      = f_lookupname(lookupprefix,"l",lookupid+lookupidoffset),
                            steps     = steps,
                            nofsteps  = nofsteps,
                            type      = lookuptype,
                            markclass = markclass or nil,
                            flags     = flags,
                         -- chain     = chain,
                        }
                        sublookuplist[nofsublookups] = l
                        sublookuphash[lookupid] = nofsublookups
                        sublookupcheck[lookupid] = 0
                        lookup.done = l
                    end
                else
                    report("no subtables for lookup %a",lookupid)
                end
            else
                report("no handler for lookup %a with type %a",lookupid,lookuptype)
            end
        end

        -- When we have a context, we have sublookups that resolve into lookups for which we need to
        -- know the type. We split the main lookuptable in two parts: sequences (the main lookups)
        -- and subtable lookups (simple specs with no features). We could keep them merged and might do
        -- that once we only use this loader. Then we can also move the simple specs into the sequence.
        -- After all, we pack afterwards.

        local reported = { }

        local function report_issue(i,what,sequence,kind)
            local name = sequence.name
            if not reported[name] then
                report("rule %i in %s lookup %a has %s lookups",i,what,name,kind)
                reported[name] = true
            end
        end

        for i=lastsequence+1,nofsequences do
            local sequence = sequences[i]
            local steps    = sequence.steps
            for i=1,#steps do
                local step  = steps[i]
                local rules = step.rules
                if rules then
                    for i=1,#rules do
                        local rule     = rules[i]
                        local rlookups = rule.lookups
                        if not rlookups then
                            report_issue(i,what,sequence,"no")
                        elseif not next(rlookups) then
                            -- can be ok as it aborts a chain sequence
                            report_issue(i,what,sequence,"empty")
                            rule.lookups = nil
                        else
                            -- we can have holes in rlookups flagged false and we can have multiple lookups
                            -- applied (first time seen in seguemj)
                            local length = #rlookups
                            for index=1,length do
                                local lookuplist = rlookups[index]
                                if lookuplist then
                                    local length   = #lookuplist
                                    local found    = { }
                                    local noffound = 0
                                    for index=1,length do
                                        local lookupid = lookuplist[index]
                                        if lookupid then
                                            local h = sublookuphash[lookupid]
                                            if not h then
                                                -- here we have a lookup that is used independent as well
                                                -- as in another one
                                                local lookup = lookups[lookupid]
                                                if lookup then
                                                    local d = lookup.done
                                                    if d then
                                                        nofsublookups = nofsublookups + 1
                                                     -- report("registering %i as sublookup %i",lookupid,nofsublookups)
                                                        h = {
                                                            index     = nofsublookups, -- handy for tracing
                                                            name      = f_lookupname(lookupprefix,"d",lookupid+lookupidoffset),
                                                            derived   = true,          -- handy for tracing
                                                            steps     = d.steps,
                                                            nofsteps  = d.nofsteps,
                                                            type      = d.lookuptype or "gsub_single", -- todo: check type
                                                            markclass = d.markclass or nil,
                                                            flags     = d.flags,
                                                         -- chain     = d.chain,
                                                        }
                                                        sublookuplist[nofsublookups] = copy(h) -- we repack later
                                                        sublookuphash[lookupid] = nofsublookups
                                                        sublookupcheck[lookupid] = 1
                                                        h = nofsublookups
                                                    else
                                                        report_issue(i,what,sequence,"missing")
                                                        rule.lookups = nil
                                                        break
                                                    end
                                                else
                                                    report_issue(i,what,sequence,"bad")
                                                    rule.lookups = nil
                                                    break
                                                end
                                            else
                                                sublookupcheck[lookupid] = sublookupcheck[lookupid] + 1
                                            end
                                            if h then
                                                noffound = noffound + 1
                                                found[noffound] = h
                                            end
                                        end
                                    end
                                    rlookups[index] = noffound > 0 and found or false
                                else
                                    rlookups[index] = false
                                end
                            end
                        end
                    end
                end
            end
        end

        for i, n in sortedhash(sublookupcheck) do
            local l = lookups[i]
            local t = l.type
            if n == 0 and t ~= "extension" then
                local d = l.done
                report("%s lookup %s of type %a is not used",what,d and d.name or l.name,t)
            end
        end

    end

    local function loadvariations(f,fontdata,variationsoffset,lookuptypes,featurehash,featureorder)
        setposition(f,variationsoffset)
        local version    = readulong(f)
        local nofrecords = readulong(f)
        local records    = { }
        for i=1,nofrecords do
            records[i] = {
                conditions    = readulong(f),
                substitutions = readulong(f),
            }
        end
        for i=1,nofrecords do
            local record = records[i]
            local offset = record.conditions
            if offset == 0 then
                record.condition = nil
                record.matchtype = "always"
            else
                setposition(f,variationsoffset+offset)
                local nofconditions = readushort(f)
                local conditions    = { }
                for i=1,nofconditions do
                    conditions[i] = variationsoffset+offset+readulong(f)
                end
                record.conditions = conditions
                record.matchtype  = "condition"
            end
        end
        for i=1,nofrecords do
            local record = records[i]
            if record.matchtype == "condition" then
                local conditions = record.conditions
                for i=1,#conditions do
                    setposition(f,conditions[i])
                    conditions[i] = {
                        format   = readushort(f),
                        axis     = readushort(f),
                        minvalue = read2dot14(f),
                        maxvalue = read2dot14(f),
                    }
                end
            end
        end

        for i=1,nofrecords do
            local record = records[i]
            local offset = record.substitutions
            if offset == 0 then
                record.substitutions = { }
            else
                setposition(f,variationsoffset + offset)
                local version          = readulong(f)
                local nofsubstitutions = readushort(f)
                local substitutions    = { }
                for i=1,nofsubstitutions do
                    substitutions[readushort(f)] = readulong(f)
                end
                for index, alternates in sortedhash(substitutions) do
                    if index == 0 then
                        record.substitutions = false
                    else
                        local tableoffset = variationsoffset + offset + alternates
                        setposition(f,tableoffset)
                        local parameters = readulong(f) -- feature parameters
                        local noflookups = readushort(f)
                        local lookups    = { }
                        for i=1,noflookups do
                            lookups[i] = readushort(f) -- not sure what to do with these
                        end
                        -- todo : resolve to proper lookups
                        record.substitutions = lookups
                    end
                end
            end
        end
        setvariabledata(fontdata,"features",records)
    end

    local function readscripts(f,fontdata,what,lookuptypes,lookuphandlers,lookupstoo)
        local tableoffset = gotodatatable(f,fontdata,what,true)
        if tableoffset then
            local version          = readulong(f)
            local scriptoffset     = tableoffset + readushort(f)
            local featureoffset    = tableoffset + readushort(f)
            local lookupoffset     = tableoffset + readushort(f)
            local variationsoffset = version > 0x00010000 and (tableoffset + readulong(f)) or 0
            if not scriptoffset then
                return
            end
            local scripts  = readscriplan(f,fontdata,scriptoffset)
            local features = readfeatures(f,fontdata,featureoffset)
            --
            local scriptlangs, featurehash, featureorder = reorderfeatures(fontdata,scripts,features)
            --
            if fontdata.features then
                fontdata.features[what] = scriptlangs
            else
                fontdata.features = { [what] = scriptlangs }
            end
            --
            if not lookupstoo then
                return
            end
            --
            local lookups = readlookups(f,lookupoffset,lookuptypes,featurehash,featureorder)
            --
            if lookups then
                resolvelookups(f,lookupoffset,fontdata,lookups,lookuptypes,lookuphandlers,what,tableoffset)
            end
            --
            if variationsoffset > 0 then
                loadvariations(f,fontdata,variationsoffset,lookuptypes,featurehash,featureorder)
            end
        end
    end

    local function checkkerns(f,fontdata,specification)
        local datatable = fontdata.tables.kern
        if not datatable then
            return -- no kerns
        end
        local features     = fontdata.features
        local gposfeatures = features and features.gpos
        local name
        if not gposfeatures or not gposfeatures.kern then
            name = "kern"
        elseif specification.globalkerns then
            name = "globalkern"
        else
            report("ignoring global kern table using gpos kern feature")
            return
        end
        setposition(f,datatable.offset)
        local version   = readushort(f)
        local noftables = readushort(f)
        if noftables > 1 then
            report("adding global kern table as gpos feature %a",name)
            local kerns = setmetatableindex("table")
            for i=1,noftables do
                local version  = readushort(f)
                local length   = readushort(f)
                local coverage = readushort(f)
                -- bit 8-15 of coverage: format 0 or 2
                local format   = bit32.rshift(coverage,8) -- is this ok
                if format == 0 then
                    local nofpairs      = readushort(f)
                    local searchrange   = readushort(f)
                    local entryselector = readushort(f)
                    local rangeshift    = readushort(f)
                    for i=1,nofpairs do
                        kerns[readushort(f)][readushort(f)] = readfword(f)
                    end
                elseif format == 2 then
                    -- apple specific so let's ignore it
                else
                    -- not supported by ms
                end
            end
            local feature = { dflt = { dflt = true } }
            if not features then
                fontdata.features = { gpos = { [name] = feature } }
            elseif not gposfeatures then
                fontdata.features.gpos = { [name] = feature }
            else
                gposfeatures[name] = feature
            end
            local sequences = fontdata.sequences
            if not sequences then
                sequences = { }
                fontdata.sequences = sequences
            end
            local nofsequences = #sequences + 1
            sequences[nofsequences] = {
                index     = nofsequences,
                name      = name,
                steps     = {
                    {
                        coverage = kerns,
                        format   = "kern",
                    },
                },
                nofsteps  = 1,
                type      = "gpos_pair",
             -- type      = "gpos_single", -- maybe better
                flags     = { false, false, false, false },
                order     = { name },
                features  = { [name] = feature },
            }
        else
            report("ignoring empty kern table of feature %a",name)
        end
    end

    function readers.gsub(f,fontdata,specification)
        if specification.details then
            readscripts(f,fontdata,"gsub",gsubtypes,gsubhandlers,specification.lookups)
        end
    end

    function readers.gpos(f,fontdata,specification)
        if specification.details then
            readscripts(f,fontdata,"gpos",gpostypes,gposhandlers,specification.lookups)
            if specification.lookups then
                checkkerns(f,fontdata,specification)
            end
        end
    end

end

function readers.gdef(f,fontdata,specification)
    if not specification.glyphs then
        return
    end
    local datatable = fontdata.tables.gdef
    if datatable then
        local tableoffset = datatable.offset
        setposition(f,tableoffset)
        local version          = readulong(f)
        local classoffset      = tableoffset + readushort(f)
        local attachmentoffset = tableoffset + readushort(f) -- used for bitmaps
        local ligaturecarets   = tableoffset + readushort(f) -- used in editors (maybe nice for tracing)
        local markclassoffset  = tableoffset + readushort(f)
        local marksetsoffset   = version >= 0x00010002 and (tableoffset + readushort(f))
        local varsetsoffset    = version >= 0x00010003 and (tableoffset + readulong(f))
        local glyphs           = fontdata.glyphs
        local marks            = { }
        local markclasses      = setmetatableindex("table")
        local marksets         = setmetatableindex("table")
        fontdata.marks         = marks
        fontdata.markclasses   = markclasses
        fontdata.marksets      = marksets
        -- class definitions
        setposition(f,classoffset)
        local classformat = readushort(f)
        if classformat == 1 then
            local firstindex = readushort(f)
            local lastindex  = firstindex + readushort(f) - 1
            for index=firstindex,lastindex do
                local class = classes[readushort(f)]
                if class == "mark" then
                    marks[index] = true
                end
                glyphs[index].class = class
            end
        elseif classformat == 2 then
            local nofranges = readushort(f)
            for i=1,nofranges do
                local firstindex = readushort(f)
                local lastindex  = readushort(f)
                local class      = classes[readushort(f)]
                if class then
                    for index=firstindex,lastindex do
                        glyphs[index].class = class
                        if class == "mark" then
                            marks[index] = true
                        end
                    end
                end
            end
        end
        -- mark classes
        setposition(f,markclassoffset)
        local classformat = readushort(f)
        if classformat == 1 then
            local firstindex = readushort(f)
            local lastindex  = firstindex + readushort(f) - 1
            for index=firstindex,lastindex do
                markclasses[readushort(f)][index] = true
            end
        elseif classformat == 2 then
            local nofranges = readushort(f)
            for i=1,nofranges do
                local firstindex = readushort(f)
                local lastindex  = readushort(f)
                local class      = markclasses[readushort(f)]
                for index=firstindex,lastindex do
                    class[index] = true
                end
            end
        end
        -- mark sets : todo: just make the same as class sets above
        if marksetsoffset and marksetsoffset > tableoffset then -- zero offset means no table
            setposition(f,marksetsoffset)
            local format = readushort(f)
            if format == 1 then
                local nofsets = readushort(f)
                local sets    = { }
                for i=1,nofsets do
                    sets[i] = readulong(f)
                end
                for i=1,nofsets do
                    local offset = sets[i]
                    if offset ~= 0 then
                        marksets[i] = readcoverage(f,marksetsoffset+offset)
                    end
                end
            end
        end

        local factors = specification.factors

        if (specification.variable or factors) and varsetsoffset and varsetsoffset > tableoffset then

            local regions, deltas = readvariationdata(f,varsetsoffset,factors)

         -- setvariabledata(fontdata,"gregions",regions)

            if factors then
                fontdata.temporary.getdelta = function(outer,inner)
                    local delta = deltas[outer+1]
                    if delta then
                        local d = delta.deltas[inner+1]
                        if d then
                            local scales = delta.scales
                            local dd = 0
                            for i=1,#scales do
                                local di = d[i]
                                if di then
                                    dd = dd + scales[i] * di
                                else
                                    break
                                end
                            end
                            return round(dd)
                        end
                    end
                    return 0
                end
            end

        end
    end
end

-- We keep this code here instead of font-otm.lua because we need coverage
-- helpers. Okay, these helpers could go to the main reader file some day.

local function readmathvalue(f)
    local v = readshort(f)
    skipshort(f,1) -- offset to device table
    return v
end

local function readmathconstants(f,fontdata,offset)
    setposition(f,offset)
    fontdata.mathconstants = {
        ScriptPercentScaleDown                   = readshort(f),
        ScriptScriptPercentScaleDown             = readshort(f),
        DelimitedSubFormulaMinHeight             = readushort(f),
        DisplayOperatorMinHeight                 = readushort(f),
        MathLeading                              = readmathvalue(f),
        AxisHeight                               = readmathvalue(f),
        AccentBaseHeight                         = readmathvalue(f),
        FlattenedAccentBaseHeight                = readmathvalue(f),
        SubscriptShiftDown                       = readmathvalue(f),
        SubscriptTopMax                          = readmathvalue(f),
        SubscriptBaselineDropMin                 = readmathvalue(f),
        SuperscriptShiftUp                       = readmathvalue(f),
        SuperscriptShiftUpCramped                = readmathvalue(f),
        SuperscriptBottomMin                     = readmathvalue(f),
        SuperscriptBaselineDropMax               = readmathvalue(f),
        SubSuperscriptGapMin                     = readmathvalue(f),
        SuperscriptBottomMaxWithSubscript        = readmathvalue(f),
        SpaceAfterScript                         = readmathvalue(f),
        UpperLimitGapMin                         = readmathvalue(f),
        UpperLimitBaselineRiseMin                = readmathvalue(f),
        LowerLimitGapMin                         = readmathvalue(f),
        LowerLimitBaselineDropMin                = readmathvalue(f),
        StackTopShiftUp                          = readmathvalue(f),
        StackTopDisplayStyleShiftUp              = readmathvalue(f),
        StackBottomShiftDown                     = readmathvalue(f),
        StackBottomDisplayStyleShiftDown         = readmathvalue(f),
        StackGapMin                              = readmathvalue(f),
        StackDisplayStyleGapMin                  = readmathvalue(f),
        StretchStackTopShiftUp                   = readmathvalue(f),
        StretchStackBottomShiftDown              = readmathvalue(f),
        StretchStackGapAboveMin                  = readmathvalue(f),
        StretchStackGapBelowMin                  = readmathvalue(f),
        FractionNumeratorShiftUp                 = readmathvalue(f),
        FractionNumeratorDisplayStyleShiftUp     = readmathvalue(f),
        FractionDenominatorShiftDown             = readmathvalue(f),
        FractionDenominatorDisplayStyleShiftDown = readmathvalue(f),
        FractionNumeratorGapMin                  = readmathvalue(f),
        FractionNumeratorDisplayStyleGapMin      = readmathvalue(f),
        FractionRuleThickness                    = readmathvalue(f),
        FractionDenominatorGapMin                = readmathvalue(f),
        FractionDenominatorDisplayStyleGapMin    = readmathvalue(f),
        SkewedFractionHorizontalGap              = readmathvalue(f),
        SkewedFractionVerticalGap                = readmathvalue(f),
        OverbarVerticalGap                       = readmathvalue(f),
        OverbarRuleThickness                     = readmathvalue(f),
        OverbarExtraAscender                     = readmathvalue(f),
        UnderbarVerticalGap                      = readmathvalue(f),
        UnderbarRuleThickness                    = readmathvalue(f),
        UnderbarExtraDescender                   = readmathvalue(f),
        RadicalVerticalGap                       = readmathvalue(f),
        RadicalDisplayStyleVerticalGap           = readmathvalue(f),
        RadicalRuleThickness                     = readmathvalue(f),
        RadicalExtraAscender                     = readmathvalue(f),
        RadicalKernBeforeDegree                  = readmathvalue(f),
        RadicalKernAfterDegree                   = readmathvalue(f),
        RadicalDegreeBottomRaisePercent          = readshort(f),
    }
end

local function readmathglyphinfo(f,fontdata,offset)
    setposition(f,offset)
    local italics    = readushort(f)
    local accents    = readushort(f)
    local extensions = readushort(f)
    local kerns      = readushort(f)
    local glyphs     = fontdata.glyphs
    if italics ~= 0 then
        setposition(f,offset+italics)
        local coverage  = readushort(f)
        local nofglyphs = readushort(f)
        coverage = readcoverage(f,offset+italics+coverage,true)
        setposition(f,offset+italics+4)
        for i=1,nofglyphs do
            local italic = readmathvalue(f)
            if italic ~= 0 then
                local glyph = glyphs[coverage[i]]
                local math  = glyph.math
                if not math then
                    glyph.math = { italic = italic }
                else
                    math.italic = italic
                end
            end
        end
        fontdata.hasitalics = true
    end
    if accents ~= 0 then
        setposition(f,offset+accents)
        local coverage  = readushort(f)
        local nofglyphs = readushort(f)
        coverage = readcoverage(f,offset+accents+coverage,true)
        setposition(f,offset+accents+4)
        for i=1,nofglyphs do
            local accent = readmathvalue(f)
            if accent ~= 0 then
                local glyph = glyphs[coverage[i]]
                local math  = glyph.math
                if not math then
                    glyph.math = { accent = accent }
                else
                    math.accent = accent
                end
            end
        end
    end
    if extensions ~= 0 then
        setposition(f,offset+extensions)
    end
    if kerns ~= 0 then
        local kernoffset = offset + kerns
        setposition(f,kernoffset)
        local coverage  = readushort(f)
        local nofglyphs = readushort(f)
        if nofglyphs > 0 then
            local function get(offset)
                setposition(f,kernoffset+offset)
                local n = readushort(f)
                if n == 0 then
                    local k = readmathvalue(f)
                    if k == 0 then
                        -- no need for it (happens sometimes)
                    else
                        return { { kern = k } }
                    end
                else
                    local l = { }
                    for i=1,n do
                        l[i] = { height = readmathvalue(f) }
                    end
                    for i=1,n do
                        l[i].kern = readmathvalue(f)
                    end
                    l[n+1] = { kern = readmathvalue(f) }
                    return l
                end
            end
            local kernsets = { }
            for i=1,nofglyphs do
                local topright    = readushort(f)
                local topleft     = readushort(f)
                local bottomright = readushort(f)
                local bottomleft  = readushort(f)
                kernsets[i] = {
                    topright    = topright    ~= 0 and topright    or nil,
                    topleft     = topleft     ~= 0 and topleft     or nil,
                    bottomright = bottomright ~= 0 and bottomright or nil,
                    bottomleft  = bottomleft  ~= 0 and bottomleft  or nil,
                }
            end
            coverage = readcoverage(f,kernoffset+coverage,true)
            for i=1,nofglyphs do
                local kernset = kernsets[i]
                if next(kernset) then
                    local k = kernset.topright    if k then kernset.topright    = get(k) end
                    local k = kernset.topleft     if k then kernset.topleft     = get(k) end
                    local k = kernset.bottomright if k then kernset.bottomright = get(k) end
                    local k = kernset.bottomleft  if k then kernset.bottomleft  = get(k) end
                    if next(kernset) then
                        local glyph = glyphs[coverage[i]]
                        local math  = glyph.math
                        if math then
                            math.kerns = kernset
                        else
                            glyph.math = { kerns = kernset }
                        end
                    end
                end
            end
        end
    end
end

local function readmathvariants(f,fontdata,offset)
    setposition(f,offset)
    local glyphs        = fontdata.glyphs
    local minoverlap    = readushort(f)
    local vcoverage     = readushort(f)
    local hcoverage     = readushort(f)
    local vnofglyphs    = readushort(f)
    local hnofglyphs    = readushort(f)
    local vconstruction = { }
    local hconstruction = { }
    for i=1,vnofglyphs do
        vconstruction[i] = readushort(f)
    end
    for i=1,hnofglyphs do
        hconstruction[i] = readushort(f)
    end

    fontdata.mathconstants.MinConnectorOverlap = minoverlap

    -- variants[i] = {
    --     glyph   = readushort(f),
    --     advance = readushort(f),
    -- }

    local function get(offset,coverage,nofglyphs,construction,kvariants,kparts,kitalic)
        if coverage ~= 0 and nofglyphs > 0 then
            local coverage = readcoverage(f,offset+coverage,true)
            for i=1,nofglyphs do
                local c = construction[i]
                if c ~= 0 then
                    local index = coverage[i]
                    local glyph = glyphs[index]
                    local math  = glyph.math
                    setposition(f,offset+c)
                    local assembly    = readushort(f)
                    local nofvariants = readushort(f)
                    if nofvariants > 0 then
                        local variants, v = nil, 0
                        for i=1,nofvariants do
                            local variant = readushort(f)
                            if variant == index then
                                -- ignore
                            elseif variants then
                                v = v + 1
                                variants[v] = variant
                            else
                                v = 1
                                variants = { variant }
                            end
                            skipshort(f)
                        end
                        if not variants then
                            -- only self
                        elseif not math then
                            math = { [kvariants] = variants }
                            glyph.math = math
                        else
                            math[kvariants] = variants
                        end
                    end
                    if assembly ~= 0 then
                        setposition(f,offset + c + assembly)
                        local italic   = readmathvalue(f)
                        local nofparts = readushort(f)
                        local parts    = { }
                        for i=1,nofparts do
                            local p = {
                                glyph   = readushort(f),
                                start   = readushort(f),
                                ["end"] = readushort(f),
                                advance = readushort(f),
                            }
                            local flags = readushort(f)
                            if bittest(flags,0x0001) then
                                p.extender = 1 -- true
                            end
                            parts[i] = p
                        end
                        if not math then
                            math = {
                                [kparts] = parts
                            }
                            glyph.math = math
                        else
                            math[kparts] = parts
                        end
                        if italic and italic ~= 0 then
                            math[kitalic] = italic
                        end
                    end
                end
            end
        end
    end

    get(offset,vcoverage,vnofglyphs,vconstruction,"vvariants","vparts","vitalic")
    get(offset,hcoverage,hnofglyphs,hconstruction,"hvariants","hparts","hitalic")
end

function readers.math(f,fontdata,specification)
    local tableoffset = gotodatatable(f,fontdata,"math",specification.glyphs)
    if tableoffset then
        local version = readulong(f)
     -- if version ~= 0x00010000 then
     --     report("table version %a of %a is not supported (yet), maybe font %s is bad",version,"math",fontdata.filename)
     --     return
     -- end
        local constants = readushort(f)
        local glyphinfo = readushort(f)
        local variants  = readushort(f)
        if constants == 0 then
            report("the math table of %a has no constants",fontdata.filename)
        else
            readmathconstants(f,fontdata,tableoffset+constants)
        end
        if glyphinfo ~= 0 then
            readmathglyphinfo(f,fontdata,tableoffset+glyphinfo)
        end
        if variants ~= 0 then
            readmathvariants(f,fontdata,tableoffset+variants)
        end
    end
end

function readers.colr(f,fontdata,specification)
    local tableoffset = gotodatatable(f,fontdata,"colr",specification.glyphs)
    if tableoffset then
        local version = readushort(f)
        if version ~= 0 then
            report("table version %a of %a is not supported (yet), maybe font %s is bad",version,"colr",fontdata.filename)
            return
        end
        if not fontdata.tables.cpal then
            report("color table %a in font %a has no mandate %a table","colr",fontdata.filename,"cpal")
            fontdata.colorpalettes = { }
        end
        local glyphs       = fontdata.glyphs
        local nofglyphs    = readushort(f)
        local baseoffset   = readulong(f)
        local layeroffset  = readulong(f)
        local noflayers    = readushort(f)
        local layerrecords = { }
        local maxclass     = 0
        -- The special value 0xFFFF is foreground (but we index from 1). It
        -- more looks like indices into a palette so 'class' is a better name
        -- than 'palette'.
        setposition(f,tableoffset + layeroffset)
        for i=1,noflayers do
            local slot  = readushort(f)
            local class = readushort(f)
            if class < 0xFFFF then
                class = class + 1
                if class > maxclass then
                    maxclass = class
                end
            end
            layerrecords[i] = {
                slot  = slot,
                class = class,
            }
        end
        fontdata.maxcolorclass = maxclass
        setposition(f,tableoffset + baseoffset)
        for i=0,nofglyphs-1 do
            local glyphindex = readushort(f)
            local firstlayer = readushort(f)
            local noflayers  = readushort(f)
            local t = { }
            for i=1,noflayers do
                t[i] = layerrecords[firstlayer+i]
            end
            glyphs[glyphindex].colors = t
        end
    end
    fontdata.hascolor = true
end

function readers.cpal(f,fontdata,specification)
    local tableoffset = gotodatatable(f,fontdata,"cpal",specification.glyphs)
    if tableoffset then
        local version = readushort(f)
     -- if version > 1 then
     --     report("table version %a of %a is not supported (yet), maybe font %s is bad",version,"cpal",fontdata.filename)
     --     return
     -- end
        local nofpaletteentries  = readushort(f)
        local nofpalettes        = readushort(f)
        local nofcolorrecords    = readushort(f)
        local firstcoloroffset   = readulong(f)
        local colorrecords       = { }
        local palettes           = { }
        for i=1,nofpalettes do
            palettes[i] = readushort(f)
        end
        if version == 1 then
            -- used for guis
            local palettettypesoffset = readulong(f)
            local palettelabelsoffset = readulong(f)
            local paletteentryoffset  = readulong(f)
        end
        setposition(f,tableoffset+firstcoloroffset)
        for i=1,nofcolorrecords do
            local b, g, r, a = readbytes(f,4)
            colorrecords[i] = {
                r, g, b, a ~= 255 and a or nil,
            }
        end
        for i=1,nofpalettes do
            local p = { }
            local o = palettes[i]
            for j=1,nofpaletteentries do
                p[j] = colorrecords[o+j]
            end
            palettes[i] = p
        end
        fontdata.colorpalettes = palettes
    end
end

function readers.svg(f,fontdata,specification)
    local tableoffset = gotodatatable(f,fontdata,"svg",specification.glyphs)
    if tableoffset then
        local version = readushort(f)
     -- if version ~= 0 then
     --     report("table version %a of %a is not supported (yet), maybe font %s is bad",version,"svg",fontdata.filename)
     --     return
     -- end
        local glyphs      = fontdata.glyphs
        local indexoffset = tableoffset + readulong(f)
        local reserved    = readulong(f)
        setposition(f,indexoffset)
        local nofentries  = readushort(f)
        local entries     = { }
        for i=1,nofentries do
            entries[i] = {
                first  = readushort(f),
                last   = readushort(f),
                offset = indexoffset + readulong(f),
                length = readulong(f),
            }
        end
        for i=1,nofentries do
            local entry = entries[i]
            setposition(f,entry.offset)
            entries[i] = {
                first = entry.first,
                last  = entry.last,
                data  = readstring(f,entry.length)
            }
        end
        fontdata.svgshapes = entries
    end
    fontdata.hascolor = true
end

function readers.sbix(f,fontdata,specification)
    local tableoffset = gotodatatable(f,fontdata,"sbix",specification.glyphs)
    if tableoffset then
        local version    = readushort(f)
        local flags      = readushort(f)
        local nofstrikes = readulong(f)
        local strikes    = { }
        local nofglyphs  = fontdata.nofglyphs
        for i=1,nofstrikes do
            strikes[i] = readulong(f)
        end
     -- if true then
            local shapes = { }
            local done   = 0
            for i=1,nofstrikes do
                local strikeoffset = strikes[i] + tableoffset
                setposition(f,strikeoffset)
                strikes[i] = {
                    ppem   = readushort(f),
                    ppi    = readushort(f),
                    offset = strikeoffset
                }
            end
            -- highest first
            sort(strikes,function(a,b)
                if b.ppem == a.ppem then
                    return b.ppi < a.ppi
                else
                    return b.ppem < a.ppem
                end
            end)
            local glyphs = { }
            for i=1,nofstrikes do
                local strike = strikes[i]
                local strikeppem   = strike.ppem
                local strikeppi    = strike.ppi
                local strikeoffset = strike.offset
                setposition(f,strikeoffset)
                for i=0,nofglyphs do
                    glyphs[i] = readulong(f)
                end
                local glyphoffset = glyphs[0]
                for i=0,nofglyphs-1 do
                    local nextoffset = glyphs[i+1]
                    if not shapes[i] then
                        local datasize = nextoffset - glyphoffset
                        if datasize > 0 then
                            setposition(f,strikeoffset + glyphoffset)
                            shapes[i] = {
                                x    = readshort(f),
                                y    = readshort(f),
                                tag  = readtag(f), -- maybe for tracing
                                data = readstring(f,datasize-8),
                                ppem = strikeppem, -- not used, for tracing
                                ppi  = strikeppi,  -- not used, for tracing
                            }
                            done = done + 1
                            if done == nofglyphs then
                                break
                            end
                        end
                    end
                    glyphoffset = nextoffset
                end
            end
            fontdata.sbixshapes = shapes
     -- else
     --     for i=1,nofstrikes do
     --         local strikeoffset = strikes[i] + tableoffset
     --         setposition(f,strikeoffset)
     --         local glyphs = { }
     --         strikes[i] = {
     --             ppem   = readushort(f),
     --             ppi    = readushort(f),
     --             glyphs = glyphs,
     --         }
     --         for i=0,nofglyphs do
     --             glyphs[i] = readulong(f)
     --         end
     --         local glyphoffset = glyphs[0]
     --         for i=0,nofglyphs-1 do
     --             local nextoffset = glyphs[i+1]
     --             local datasize   = nextoffset - glyphoffset
     --             if datasize > 0 then
     --                 setposition(f,strikeoffset + glyphoffset)
     --                 glyphs[i] = {
     --                     x    = readshort(f),
     --                     y    = readshort(f),
     --                     tag  = readtag(f),
     --                     data = readstring(f,datasize-8)
     --                 }
     --                 glyphoffset = nextoffset
     --             end
     --         end
     --     end
     --     fontdata.sbixshapes = strikes
     -- end
    end
end

-- function readers.cblc(f,fontdata,specification)
--     local tableoffset = gotodatatable(f,fontdata,"cblc",specification.glyphs)
--     if tableoffset then
--     end
-- end
--
-- function readers.cbdt(f,fontdata,specification)
--     local tableoffset = gotodatatable(f,fontdata,"ctdt",specification.glyphs)
--     if tableoffset then
--
--         local function getmetrics(f)
--             return {
--                 ascender              = readinteger(f),
--                 descender             = readinteger(f),
--                 widthmax              = readcardinal(f),
--                 caretslopedumerator   = readinteger(f),
--                 caretslopedenominator = readinteger(f),
--                 caretoffset           = readinteger(f),
--                 minorigin             = readinteger(f),
--                 minadvance            = readinteger(f),
--                 maxbefore             = readinteger(f),
--                 minafter              = readinteger(f),
--                 pad1                  = readinteger(f),
--                 pad2                  = readinteger(f),
--             }
--         end
--
--         local majorversion  = readushort(f)
--         local minorversion  = readushort(f)
--         local nofsizetables = readulong(f)
--         local sizetable     = { }
--         for i=1,nofsizetables do
--             sizetable[i] = {
--                 subtables    = readulong(f),
--                 indexsize    = readulong(f),
--                 nofsubtables = readulong(f),
--                 colorref     = readulong(f),
--                 hormetrics   = getmetrics(f),
--                 vermetrics   = getmetrics(f),
--                 firstindex   = readushort(f),
--                 lastindex    = readushort(f),
--                 ppemx        = readbyte(f),
--                 ppemy        = readbyte(f),
--                 bitdepth     = readbyte(f),
--                 flags        = readbyte(f),
--             }
--         end
--
--         sort(sizetable,function(a,b)
--             if b.ppemx == a.ppemx then
--                 return b.bitdepth < a.bitdepth
--             else
--                 return b.ppemx < a.ppemx
--             end
--         end)
--
--         local shapes = { }
--
--         for i=1,nofsizetables do
--             local s = sizetables[i]
--             for j=firstindex,lastindex do
--                 if not shapes[j] then
--                     shapes[j] = {
--                         i
--                     }
--                 end
--             end
--         end
--
--         inspect(shapes)
--
--     end
-- end

-- function readers.ebdt(f,fontdata,specification)
--     if specification.glyphs then
--     end
-- end

-- function readers.ebsc(f,fontdata,specification)
--     if specification.glyphs then
--     end
-- end

-- function readers.eblc(f,fontdata,specification)
--     if specification.glyphs then
--     end
-- end

-- + AVAR : optional
-- + CFF2 : otf outlines
-- - CVAR : ttf hinting, not needed
-- + FVAR : the variations
-- + GVAR : ttf outline changes
-- + HVAR : horizontal changes
-- + MVAR : metric changes
-- + STAT : relations within fonts
-- * VVAR : vertical changes
--
-- * BASE : extra baseline adjustments
-- - GASP : not needed
-- + GDEF : not needed (carets)
-- + GPOS : adapted device tables (needed?)
-- + GSUB : new table
-- + NAME : 25 added

function readers.stat(f,fontdata,specification)
    local tableoffset = gotodatatable(f,fontdata,"stat",true) -- specification.variable
    if tableoffset then
        local extras       = fontdata.extras
        local version      = readulong(f) -- 0x00010000
        local axissize     = readushort(f)
        local nofaxis      = readushort(f)
        local axisoffset   = readulong(f)
        local nofvalues    = readushort(f)
        local valuesoffset = readulong(f)
        local fallbackname = extras[readushort(f)] -- beta fonts mess up
        local axis         = { }
        local values       = { }
        setposition(f,tableoffset+axisoffset)
        for i=1,nofaxis do
            axis[i] = {
                tag      = readtag(f),
                name     = lower(extras[readushort(f)]),
                ordering = readushort(f), -- maybe gaps
                variants = { }
            }
        end
        -- flags:
        --
        -- 0x0001 : OlderSiblingFontAttribute
        -- 0x0002 : ElidableAxisValueName
        -- 0xFFFC : reservedFlags
        --
        setposition(f,tableoffset+valuesoffset)
        for i=1,nofvalues do
            values[i] = readushort(f)
        end
        for i=1,nofvalues do
            setposition(f,tableoffset + valuesoffset + values[i])
            local format  = readushort(f)
            local index   = readushort(f) + 1
            local flags   = readushort(f)
            local name    = lower(extras[readushort(f)])
            local value   = readfixed(f)
            local variant
            if format == 1 then
                variant = {
                    flags = flags,
                    name  = name,
                    value = value,
                }
            elseif format == 2 then
                variant = {
                    flags   = flags,
                    name    = name,
                    value   = value,
                    minimum = readfixed(f),
                    maximum = readfixed(f),
                }
            elseif format == 3 then
                variant = {
                    flags = flags,
                    name  = name,
                    value = value,
                    link  = readfixed(f),
                }
            end
            insert(axis[index].variants,variant)
        end
        sort(axis,function(a,b)
            return a.ordering < b.ordering
        end)
        for i=1,#axis do
            local a = axis[i]
            sort(a.variants,function(a,b)
                return a.name < b.name
            end)
            a.ordering = nil
        end
        setvariabledata(fontdata,"designaxis",axis)
        setvariabledata(fontdata,"fallbackname",fallbackname)
    end
end

-- The avar table is optional and used in combination with fvar. Given the
-- detailed explanation about bad valeus we expect the worst and do some
-- checking.

function readers.avar(f,fontdata,specification)
    local tableoffset = gotodatatable(f,fontdata,"avar",true) -- specification.variable
    if tableoffset then

        local function collect()
            local nofvalues = readulong(f)
            local values    = { }
            local lastfrom  = false
            local lastto    = false
            for i=1,nofvalues do
                local f, t = read2dot14(f), read2dot14(f)
                if lastfrom and f <= lastfrom then
                    -- ignore
                elseif lastto and t >= lastto then
                    -- ignore
                else
                    values[#values+1] = { f, t }
                    lasfrom, lastto = f, t
                end
            end
            nofvalues = #values
            if nofvalues > 2 then
                local some = values[1]
                if some[1] == -1 and some[2] == -1 then
                    some = values[nofvalues]
                    if some[1] == 1 and some[2] == 1 then
                        for i=2,size-1 do
                            some = values[i]
                            if some[1] == 0 and some[2] == 0 then
                                return values
                            end
                        end
                    end
                end
            end
            return false
        end

        local version  = readulong(f) -- 1.0
        local reserved = readulong(f)
        local nofaxis  = readulong(f)
        local segments = { }
        for i=1,nofaxis do
            segments[i] = collect()
        end
        setvariabledata(fontdata,"segments",segments)
    end
end

function readers.fvar(f,fontdata,specification)
    local tableoffset = gotodatatable(f,fontdata,"fvar",true) -- specification.variable or specification.instancenames
    if tableoffset then
        local version         = readulong(f) -- 1.0
        local offsettoaxis    = tableoffset + readushort(f)
        local reserved        = skipshort(f)
        -- pair 1
        local nofaxis         = readushort(f)
        local sizeofaxis      = readushort(f)
        -- pair 2
        local nofinstances    = readushort(f)
        local sizeofinstances = readushort(f)
        --
        local extras    = fontdata.extras
        local axis      = { }
        local instances = { }
        --
        setposition(f,offsettoaxis)
        --
        for i=1,nofaxis do
            axis[i] = {
                tag     = readtag(f),   -- ital opsz slnt wdth wght
                minimum = readfixed(f), -- we get weird values from a test font ... to be checked
                default = readfixed(f), -- idem
                maximum = readfixed(f), -- idem
                flags   = readushort(f),
                name    = lower(extras[readushort(f)] or "bad name"),
            }
            local n = sizeofaxis - 20
            if n > 0 then
                skipbytes(f,n)
            elseif n < 0 then
                -- error
            end
        end
        --
        local nofbytes   = 2 + 2 + 2 + nofaxis * 4
        local readpsname = nofbytes <= sizeofinstances
        local skippable  = sizeofinstances - nofbytes
        for i=1,nofinstances do
            local subfamid = readushort(f)
            local flags    = readushort(f) -- 0, not used yet
            local values   = { }
            for i=1,nofaxis do
                -- depends on what we want to see:
                --
             -- values[axis[i].tag] = readfixed(f)
                --
                values[i] = {
                    axis  = axis[i].tag,
                    value = readfixed(f),
                }
            end
            local psnameid = readpsname and readushort(f) or 0xFFFF
            if subfamid == 2 or subfamid == 17 then
                -- okay
            elseif subfamid == 0xFFFF then
                subfamid = nil
            elseif subfamid <= 256 or subfamid >= 32768 then
                subfamid = nil -- actually an error
            end
            if psnameid == 6 then
                -- okay
            elseif psnameid == 0xFFFF then
                psnameid = nil
            elseif psnameid <= 256 or psnameid >= 32768 then
                psnameid = nil -- actually an error
            end
            instances[i] = {
             -- flags     = flags,
                subfamily = extras[subfamid],
                psname    = psnameid and extras[psnameid] or nil,
                values    = values,
            }
            if skippable > 0 then
                skipbytes(f,skippable)
            end
        end
        setvariabledata(fontdata,"axis",axis)
        setvariabledata(fontdata,"instances",instances)
    end
end

function readers.hvar(f,fontdata,specification)
    local factors = specification.factors
    if not factors then
        return
    end
    local tableoffset = gotodatatable(f,fontdata,"hvar",specification.variable)
    if not tableoffset then
        return
    end

    local version         = readulong(f) -- 1.0
    local variationoffset = tableoffset + readulong(f) -- the store
    local advanceoffset   = tableoffset + readulong(f)
    local lsboffset       = tableoffset + readulong(f)
    local rsboffset       = tableoffset + readulong(f)

    local regions    = { }
    local variations = { }
    local innerindex = { } -- size is mapcount
    local outerindex = { } -- size is mapcount

    if variationoffset > 0 then
        regions, deltas = readvariationdata(f,variationoffset,factors)
    end

    if not regions then
        -- for now .. what to do ?
        return
    end

    if advanceoffset > 0 then
        --
        -- innerIndexBitCountMask = 0x000F
        -- mapEntrySizeMask       = 0x0030
        -- reservedFlags          = 0xFFC0
        --
        -- outerIndex = entry >>       ((entryFormat & innerIndexBitCountMask) + 1)
        -- innerIndex = entry & ((1 << ((entryFormat & innerIndexBitCountMask) + 1)) - 1)
        --
        setposition(f,advanceoffset)
        local format       = readushort(f) -- todo: check
        local mapcount     = readushort(f)
        local entrysize    = rshift(band(format,0x0030),4) + 1
        local nofinnerbits = band(format,0x000F) + 1 -- n of inner bits
        local innermask    = lshift(1,nofinnerbits) - 1
        local readcardinal = read_cardinal[entrysize] -- 1 upto 4 bytes
        for i=0,mapcount-1 do
            local mapdata = readcardinal(f)
            outerindex[i] = rshift(mapdata,nofinnerbits)
            innerindex[i] = band(mapdata,innermask)
        end
        -- use last entry when no match i
        local glyphs = fontdata.glyphs
        for i=0,fontdata.nofglyphs-1 do
            local glyph = glyphs[i]
            local width = glyph.width
            if width then
                local outer = outerindex[i] or 0
                local inner = innerindex[i] or i
                if outer and inner then -- not needed
                    local delta = deltas[outer+1]
                    if delta then
                        local d = delta.deltas[inner+1]
                        if d then
                            local scales = delta.scales
                            local deltaw = 0
                            for i=1,#scales do
                                local di = d[i]
                                if di then
                                    deltaw = deltaw + scales[i] * di
                                else
                                    break -- can't happen
                                end
                            end
-- report("index: %i, outer: %i, inner: %i, deltas: %|t, scales: %|t, width: %i, delta %i",
--     i,outer,inner,d,scales,width,round(deltaw))
                            glyph.width = width + round(deltaw)
                        end
                    end
                end
            end
        end

    end

 -- if lsboffset > 0 then
 --     -- we don't use left side bearings
 -- end

 -- if rsboffset > 0 then
 --     -- we don't use right side bearings
 -- end

 -- setvariabledata(fontdata,"hregions",regions)

end

function readers.vvar(f,fontdata,specification)
    if not specification.variable then
        return
    end
end

function readers.mvar(f,fontdata,specification)
    local tableoffset = gotodatatable(f,fontdata,"mvar",specification.variable)
    if tableoffset then
        local version       = readulong(f) -- 1.0
        local reserved      = skipshort(f,1)
        local recordsize    = readushort(f)
        local nofrecords    = readushort(f)
        local offsettostore = tableoffset + readushort(f)
        local dimensions    = { }
        local factors       = specification.factors
        if factors then
            local regions, deltas = readvariationdata(f,offsettostore,factors)
            for i=1,nofrecords do
                local tag = readtag(f)
                local var = variabletags[tag]
                if var then
                    local outer = readushort(f)
                    local inner = readushort(f)
                    local delta = deltas[outer+1]
                    if delta then
                        local d = delta.deltas[inner+1]
                        if d then
                            local scales = delta.scales
                            local dd = 0
                            for i=1,#scales do
                                dd = dd + scales[i] * d[i]
                            end
                            var(fontdata,round(dd))
                        end
                    end
                else
                    skipshort(f,2)
                end
                if recordsize > 8 then -- 4 + 2 + 2
                    skipbytes(recordsize-8)
                end
            end
        end
     -- setvariabledata(fontdata,"mregions",regions)
    end
end