summaryrefslogtreecommitdiff
path: root/src/fontloader/misc/fontloader-font-oup.lua
blob: 59530af06ac6497d394a76f4e592278e51dc2652 (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
if not modules then modules = { } end modules ['font-oup'] = {
    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"
}

local next, type = next, type
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local lpegmatch = lpeg.match
local insert, remove, copy = table.insert, table.remove, table.copy

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

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

local trace_markwidth   = false  trackers.register("otf.markwidth",function(v) trace_markwidth = v end)

local readers           = fonts.handlers.otf.readers
local privateoffset     = fonts.constructors and fonts.constructors.privateoffset or 0xF0000 -- 0x10FFFF

local f_private         = formatters["P%05X"]
local f_unicode         = formatters["U%05X"]
local f_index           = formatters["I%05X"]
local f_character_y     = formatters["%C"]
local f_character_n     = formatters["[ %C ]"]

local doduplicates      = true -- can become an option (pseudo feature)

local function replaced(list,index,replacement)
    if type(list) == "number" then
        return replacement
    elseif type(replacement) == "table" then
        local t = { }
        local n = index-1
        for i=1,n do
            t[i] = list[i]
        end
        for i=1,#replacement do
            n = n + 1
            t[n] = replacement[i]
        end
        for i=index+1,#list do
            n = n + 1
            t[n] = list[i]
        end
    else
        list[index] = replacement
        return list
    end
end

local function unifyresources(fontdata,indices)
    local descriptions = fontdata.descriptions
    local resources    = fontdata.resources
    if not descriptions or not resources then
        return
    end
    --
    local variants = fontdata.resources.variants
    if variants then
        for selector, unicodes in next, variants do
            for unicode, index in next, unicodes do
                unicodes[unicode] = indices[index]
            end
        end
    end
    --
    local function remark(marks)
        if marks then
            local newmarks = { }
            for k, v in next, marks do
                local u = indices[k]
                if u then
                    newmarks[u] = v
                else
                    report("discarding mark %i",k)
                end
            end
            return newmarks
        end
    end
    --
    local marks = resources.marks
    if marks then
        resources.marks  = remark(marks)
    end
    --
    local markclasses = resources.markclasses
    if markclasses then
        for class, marks in next, markclasses do
            markclasses[class] = remark(marks)
        end
    end
    --
    local marksets = resources.marksets
    if marksets then
        for class, marks in next, marksets do
            marksets[class] = remark(marks)
        end
    end
    --
    local done = { } -- we need to deal with shared !
    --
    local duplicates = doduplicates and resources.duplicates
    if duplicates and not next(duplicates) then
        duplicates = false
    end
    --
    local function recover(cover) -- can be packed
        for i=1,#cover do
            local c = cover[i]
            if not done[c] then
                local t = { }
                for k, v in next, c do
                    t[indices[k]] = v
                end
                cover[i] = t
                done[c]  = d
            end
        end
    end
    --
    local function recursed(c) -- ligs are not packed
        local t = { }
        for g, d in next, c do
            if type(d) == "table" then
                t[indices[g]] = recursed(d)
            else
                t[g] = indices[d] -- ligature
            end
        end
        return t
    end
    --
    -- the duplicates need checking (probably only in cjk fonts): currently we only check
    -- gsub_single, gsub_alternate, gsub_multiple, gpos_single and gpos_cursive
    --
    local function unifythem(sequences)
        if not sequences then
            return
        end
        for i=1,#sequences do
            local sequence  = sequences[i]
            local kind      = sequence.type
            local steps     = sequence.steps
            local features  = sequence.features
            if steps then
                for i=1,#steps do
                    local step = steps[i]
                    if kind == "gsub_single" then
                        local c = step.coverage
                        if c then
                            local t1 = done[c]
                            if not t1 then
                                t1 = { }
                                if duplicates then
                                    for g1, d1 in next, c do
                                        local ug1 = indices[g1]
                                        local ud1 = indices[d1]
                                        t1[ug1] = ud1
                                        --
                                        local dg1 = duplicates[ug1]
                                        if dg1 then
                                            for u in next, dg1 do
                                                t1[u] = ud1
                                            end
                                        end
                                    end
                                else
                                    for g1, d1 in next, c do
                                        t1[indices[g1]] = indices[d1]
                                    end
                                end
                                done[c] = t1
                            end
                            step.coverage = t1
                        end
                    elseif kind == "gpos_pair" then
                        local c = step.coverage
                        if c then
                            local t1 = done[c]
                            if not t1 then
                                t1 = { }
                                for g1, d1 in next, c do
                                    local t2 = done[d1]
                                    if not t2 then
                                        t2 = { }
                                        for g2, d2 in next, d1 do
                                            t2[indices[g2]] = d2
                                        end
                                        done[d1] = t2
                                    end
                                    t1[indices[g1]] = t2
                                end
                                done[c] = t1
                            end
                            step.coverage = t1
                        end
                    elseif kind == "gsub_ligature" then
                        local c = step.coverage
                        if c then
                            step.coverage = recursed(c)
                        end
                    elseif kind == "gsub_alternate" or kind == "gsub_multiple" then
                        local c = step.coverage
                        if c then
                            local t1 = done[c]
                            if not t1 then
                                t1 = { }
                                if duplicates then
                                    for g1, d1 in next, c do
                                        for i=1,#d1 do
                                            d1[i] = indices[d1[i]]
                                        end
                                        local ug1 = indices[g1]
                                        t1[ug1] = d1
                                        --
                                        local dg1 = duplicates[ug1]
                                        if dg1 then
                                            for u in next, dg1 do
                                                t1[u] = copy(d1)
                                            end
                                        end
                                    end
                                else
                                    for g1, d1 in next, c do
                                        for i=1,#d1 do
                                            d1[i] = indices[d1[i]]
                                        end
                                        t1[indices[g1]] = d1
                                    end
                                end
                                done[c] = t1
                            end
                            step.coverage = t1
                        end
                    elseif kind == "gpos_mark2base" or kind == "gpos_mark2mark" or kind == "gpos_mark2ligature" then
                        local c = step.coverage
                        if c then
                            local t1 = done[c]
                            if not t1 then
                                t1 = { }
                                for g1, d1 in next, c do
                                    t1[indices[g1]] = d1
                                end
                                done[c] = t1
                            end
                            step.coverage = t1
                        end
                        local c = step.baseclasses
                        if c then
                            local t1 = done[c]
                            if not t1 then
                                for g1, d1 in next, c do
                                    local t2 = done[d1]
                                    if not t2 then
                                        t2 = { }
                                        for g2, d2 in next, d1 do
                                            t2[indices[g2]] = d2
                                        end
                                        done[d1] = t2
                                    end
                                    c[g1] = t2
                                end
                                done[c] = c
                            end
                        end
                    elseif kind == "gpos_single" then
                        local c = step.coverage
                        if c then
                            local t1 = done[c]
                            if not t1 then
                                t1 = { }
                                if duplicates then
                                    for g1, d1 in next, c do
                                        local ug1 = indices[g1]
                                        t1[ug1] = d1
                                        --
                                        local dg1 = duplicates[ug1]
                                        if dg1 then
                                            for u in next, dg1 do
                                                t1[u] = d1
                                            end
                                        end
                                    end
                                else
                                    for g1, d1 in next, c do
                                        t1[indices[g1]] = d1
                                    end
                                end
                                done[c] = t1
                            end
                            step.coverage = t1
                        end
                    elseif kind == "gpos_cursive" then
                        local c = step.coverage
                        if c then
                            local t1 = done[c]
                            if not t1 then
                                t1 = { }
                                if duplicates then
                                    for g1, d1 in next, c do
                                        local ug1 = indices[g1]
                                        t1[ug1] = d1
                                        --
                                        local dg1 = duplicates[ug1]
                                        if dg1 then
                                            -- probably needs a bit more
                                            for u in next, dg1 do
                                                t1[u] = copy(d1)
                                            end
                                        end
                                    end
                                else
                                    for g1, d1 in next, c do
                                        t1[indices[g1]] = d1
                                    end
                                end
                                done[c] = t1
                            end
                            step.coverage = t1
                        end
                    end
                    --
                    local rules = step.rules
                    if rules then
                        for i=1,#rules do
                            local rule = rules[i]
                            --
                            local before   = rule.before   if before  then recover(before)  end
                            local after    = rule.after    if after   then recover(after)   end
                            local current  = rule.current  if current then recover(current) end
                            --
                            local replacements = rule.replacements
                            if replacements then
                                if not done[replacements] then
                                    local r = { }
                                    for k, v in next, replacements do
                                        r[indices[k]] = indices[v]
                                    end
                                    rule.replacements = r
                                    done[replacements] = r
                                end
                            end
                        end
                    end
                end
            end
       end
    end
    --
    unifythem(resources.sequences)
    unifythem(resources.sublookups)
end

local function copyduplicates(fontdata)
    if doduplicates then
        local descriptions = fontdata.descriptions
        local resources    = fontdata.resources
        local duplicates   = resources.duplicates
        if duplicates then
            for u, d in next, duplicates do
                local du = descriptions[u]
                if du then
                    local t  = { f_character_y(u), "@", f_index(du.index), "->" }
                    for u in next, d do
                        if descriptions[u] then
                            t[#t+1] = f_character_n(u)
                        else
                            local c = copy(du)
                         -- c.unicode = u -- maybe
                            descriptions[u] = c
                            t[#t+1] = f_character_y(u)
                        end
                    end
                    report("duplicates: % t",t)
                else
                    -- what a mess
                end
            end
        end
    end
end

local ignore = { -- should we fix them?
    ["notdef"]            = true,
    [".notdef"]           = true,
    ["null"]              = true,
    [".null"]             = true,
    ["nonmarkingreturn"]  = true,
}


local function checklookups(fontdata,missing,nofmissing)
    local descriptions = fontdata.descriptions
    local resources    = fontdata.resources
    if missing and nofmissing and nofmissing <= 0 then
        return
    end
    --
    local singles    = { }
    local alternates = { }
    local ligatures  = { }

    if not missing then
        missing    = { }
        nofmissing = 0
        for u, d in next, descriptions do
            if not d.unicode then
                nofmissing = nofmissing + 1
                missing[u] = true
            end
        end
    end

    local function collectthem(sequences)
        if not sequences then
            return
        end
        for i=1,#sequences do
            local sequence = sequences[i]
            local kind     = sequence.type
            local steps    = sequence.steps
            if steps then
                for i=1,#steps do
                    local step = steps[i]
                    if kind == "gsub_single" then
                        local c = step.coverage
                        if c then
                            singles[#singles+1] = c
                        end
                    elseif kind == "gsub_alternate" then
                        local c = step.coverage
                        if c then
                            alternates[#alternates+1] = c
                        end
                    elseif kind == "gsub_ligature" then
                        local c = step.coverage
                        if c then
                            ligatures[#ligatures+1] = c
                        end
                    end
                end
            end
        end
    end

    collectthem(resources.sequences)
    collectthem(resources.sublookups)

    local loops = 0
    while true do
        loops = loops + 1
        local old = nofmissing
        for i=1,#singles do
            local c = singles[i]
            for g1, g2 in next, c do
                if missing[g1] then
                    local u2 = descriptions[g2].unicode
                    if u2 then
                        missing[g1] = false
                        descriptions[g1].unicode = u2
                        nofmissing = nofmissing - 1
                    end
                end
                if missing[g2] then
                    local u1 = descriptions[g1].unicode
                    if u1 then
                        missing[g2] = false
                        descriptions[g2].unicode = u1
                        nofmissing = nofmissing - 1
                    end
                end
            end
        end
        for i=1,#alternates do
            local c = alternates[i]
            -- maybe first a g1 loop and then a g2
            for g1, d1 in next, c do
                if missing[g1] then
                    for i=1,#d1 do
                        local g2 = d1[i]
                        local u2 = descriptions[g2].unicode
                        if u2 then
                            missing[g1] = false
                            descriptions[g1].unicode = u2
                            nofmissing = nofmissing - 1
                        end
                    end
                end
                if not missing[g1] then
                    for i=1,#d1 do
                        local g2 = d1[i]
                        if missing[g2] then
                            local u1 = descriptions[g1].unicode
                            if u1 then
                                missing[g2] = false
                                descriptions[g2].unicode = u1
                                nofmissing = nofmissing - 1
                            end
                        end
                    end
                end
            end
        end
        if nofmissing <= 0 then
            report("all done in %s loops",loops)
            return
        elseif old == nofmissing then
            break
        end
    end

    local t, n -- no need to insert/remove and allocate many times

    local function recursed(c)
        for g, d in next, c do
            if g ~= "ligature" then
                local u = descriptions[g].unicode
                if u then
                    n = n + 1
                    t[n] = u
                    recursed(d)
                    n = n - 1
                end
            elseif missing[d] then
                local l = { }
                local m = 0
                for i=1,n do
                    local u = t[i]
                    if type(u) == "table" then
                        for i=1,#u do
                            m = m + 1
                            l[m] = u[i]
                        end
                    else
                        m = m + 1
                        l[m] = u
                    end
                end
                missing[d] = false
                descriptions[d].unicode = l
                nofmissing = nofmissing - 1
            end
        end
    end

    if nofmissing > 0 then
        t = { }
        n = 0
        local loops = 0
        while true do
            loops = loops + 1
            local old = nofmissing
            for i=1,#ligatures do
                recursed(ligatures[i])
            end
            if nofmissing <= 0 then
                report("all done in %s loops",loops)
                return
            elseif old == nofmissing then
                break
            end
        end
        t = nil
        n = 0
    end

    if nofmissing > 0 then
        local done = { }
        for i, r in next, missing do
            if r then
                local name = descriptions[i].name or f_index(i)
                if not ignore[name] then
                    done[#done+1] = name
                end
            end
        end
        if #done > 0 then
            table.sort(done)
            report("not unicoded: % t",done)
        end
    end
end

local function unifymissing(fontdata)
    if not fonts.mappings then
        require("font-map")
        require("font-agl")
    end
    local unicodes     = { }
    local private      = fontdata.private
    local resources    = fontdata.resources
    resources.unicodes = unicodes
    for unicode, d in next, fontdata.descriptions do
        if unicode < privateoffset then
            local name = d.name
            if name then
                unicodes[name] = unicode
            end
        end
    end
    fonts.mappings.addtounicode(fontdata,fontdata.filename,checklookups)
    resources.unicodes = nil
end

local function unifyglyphs(fontdata,usenames)
    local private      = fontdata.private or privateoffset
    local glyphs       = fontdata.glyphs
    local indices      = { }
    local descriptions = { }
    local names        = usenames and { }
    local resources    = fontdata.resources
    local zero         = glyphs[0]
    local zerocode     = zero.unicode
    if not zerocode then
        zerocode       = private
        zero.unicode   = zerocode
        private        = private + 1
    end
    descriptions[zerocode] = zero
    if names then
        local name  = glyphs[0].name or f_private(zerocode)
        indices[0]  = name
        names[name] = zerocode
    else
        indices[0] = zerocode
    end
    --
    for index=1,#glyphs do
        local glyph   = glyphs[index]
        local unicode = glyph.unicode -- this is the primary one
        if not unicode then
         -- report("assigning private unicode %U to glyph indexed %05X (%s)",private,index,"unset")
            unicode = private
            -- glyph.unicode  = -1
            if names then
                local name     = glyph.name or f_private(unicode)
                indices[index] = name
                names[name]    = unicode
            else
                indices[index] = unicode
            end
            private = private + 1
        elseif descriptions[unicode] then
            -- real weird
            report("assigning private unicode %U to glyph indexed %05X (%C)",private,index,unicode)
            unicode = private
            -- glyph.unicode  = -1
            if names then
                local name     = glyph.name or f_private(unicode)
                indices[index] = name
                names[name]    = unicode
            else
                indices[index] = unicode
            end
            private = private + 1
        else
            if names then
                local name     = glyph.name or f_unicode(unicode)
                indices[index] = name
                names[name]    = unicode
            else
                indices[index] = unicode
            end
        end
        descriptions[unicode] = glyph
    end
    --
    for index=1,#glyphs do
        local math  = glyphs[index].math
        if math then
            local list = math.vparts
            if list then
                for i=1,#list do local l = list[i] l.glyph = indices[l.glyph] end
            end
            local list = math.hparts
            if list then
                for i=1,#list do local l = list[i] l.glyph = indices[l.glyph] end
            end
            local list = math.vvariants
            if list then
             -- for i=1,#list do local l = list[i] l.glyph = indices[l.glyph] end
                for i=1,#list do list[i] = indices[list[i]] end
            end
            local list = math.hvariants
            if list then
             -- for i=1,#list do local l = list[i] l.glyph = indices[l.glyph] end
                for i=1,#list do list[i] = indices[list[i]] end
            end
        end
    end
    --
    fontdata.private      = private
    fontdata.glyphs       = nil
    fontdata.names        = names
    fontdata.descriptions = descriptions
    fontdata.hashmethod   = hashmethod
    --
    return indices, names
end

local p_bogusname = (
    (P("uni") + P("UNI") + P("Uni") + P("U") + P("u")) * S("Xx")^0 * R("09","AF")^1
  + (P("identity") + P("Identity") + P("IDENTITY")) * R("09","AF")^1
  + (P("index") + P("Index") + P("INDEX")) * R("09")^1
) * P(-1)

local function stripredundant(fontdata)
    local descriptions = fontdata.descriptions
    if descriptions then
        local n = 0
        local c = 0
        for unicode, d in next, descriptions do
            local name = d.name
            if name and lpegmatch(p_bogusname,name) then
                d.name = nil
                n = n + 1
            end
            if d.class == "base" then
                d.class = nil
                c = c + 1
            end
        end
        if n > 0 then
            report("%s bogus names removed (verbose unicode)",n)
        end
        if c > 0 then
            report("%s base class tags removed (default is base)",c)
        end
    end
end

function readers.getcomponents(fontdata) -- handy for resolving ligatures when names are missing
    local resources    = fontdata.resources
    local descriptions = fontdata.descriptions
    if resources then
        local sequences = resources.sequences
        if sequences then
            local collected = { }
            for i=1,#sequences do
                local sequence = sequences[i]
                if sequence.type == "gsub_ligature" then
                    local steps  = sequence.steps
                    if steps then
                        local l = { }
                        local function traverse(p,k,v)
                            if k == "ligature" then
                                collected[v] = { unpack(l) }
                            else
                                insert(l,k)
                                for k, vv in next, v do
                                    traverse(p,k,vv)
                                end
                                remove(l)
                            end
                        end
                        for i=1,#steps do
                        -- we actually had/have this in base mode
                            local coverage = steps[i].coverage
                            if coverage then
                                for k, v in next, coverage do
                                    traverse(k,k,v)
                                end
                            end
                        end
                    end
                end
            end
            if next(collected) then
                while true do
                    local done = false
                    for k, v in next, collected do
                        for i=1,#v do
                            local vi = v[i]
                            if vi == k then
                                collected[k] = nil
                            else
                                local c = collected[vi]
                                if c then
                                    done = true
                                    local t = { }
                                    local n = i - 1
                                    for j=1,n do
                                        t[j] = t[j]
                                    end
                                    for j=1,#c do
                                        n = n + 1
                                        t[n] = c[j]
                                    end
                                    for j=i+1,#v do
                                        n = n + 1
                                        t[n] = t[j]
                                    end
                                    collected[k] = t
                                    break
                                end
                            end
                        end
                    end
                    if not done then
                        break
                    end
                end
                return collected
            end
        end
    end
end

function readers.rehash(fontdata,hashmethod) -- TODO: combine loops in one
    if not (fontdata and fontdata.glyphs) then
        return
    end
    if hashmethod == "indices" then
        fontdata.hashmethod = "indices"
    elseif hashmethod == "names" then
        fontdata.hashmethod = "names"
        local indices = unifyglyphs(fontdata,true)
        unifyresources(fontdata,indices)
        copyduplicates(fontdata)
        unifymissing(fontdata)
     -- stripredundant(fontdata)
    else
        fontdata.hashmethod = "unicode"
        local indices = unifyglyphs(fontdata)
        unifyresources(fontdata,indices)
        copyduplicates(fontdata)
        unifymissing(fontdata)
        stripredundant(fontdata)
    end
    -- maybe here components
end

function readers.checkhash(fontdata)
    local hashmethod = fontdata.hashmethod
    if hashmethod == "unicodes" then
        fontdata.names = nil -- just to be sure
    elseif hashmethod == "names" and fontdata.names then
        unifyresources(fontdata,fontdata.names)
        copyduplicates(fontdata)
        fontdata.hashmethod = "unicode"
        fontdata.names = nil -- no need for it
    else
        readers.rehash(fontdata,"unicode")
    end
end

function readers.addunicodetable(fontdata)
    local resources = fontdata.resources
    local unicodes  = resources.unicodes
    if not unicodes then
        local descriptions = fontdata.descriptions
        if descriptions then
            unicodes = { }
            resources.unicodes = unicodes
            for u, d in next, descriptions do
                local n = d.name
                if n then
                    unicodes[n] = u
                end
            end
        end
    end
end

-- for the moment here:

local concat, sort = table.concat, table.sort
local next, type, tostring = next, type, tostring

local criterium     = 1
local threshold     = 0

local trace_packing = false  trackers.register("otf.packing", function(v) trace_packing = v end)
local trace_loading = false  trackers.register("otf.loading", function(v) trace_loading = v end)

local report_otf    = logs.reporter("fonts","otf loading")

local function tabstr_normal(t)
    local s = { }
    local n = 0
    for k, v in next, t do
        n = n + 1
        if type(v) == "table" then
            s[n] = k .. ">" .. tabstr_normal(v)
        elseif v == true then
            s[n] = k .. "+" -- "=true"
        elseif v then
            s[n] = k .. "=" .. v
        else
            s[n] = k .. "-" -- "=false"
        end
    end
    if n == 0 then
        return ""
    elseif n == 1 then
        return s[1]
    else
        sort(s) -- costly but needed (occasional wrong hit otherwise)
        return concat(s,",")
    end
end

local function tabstr_flat(t)
    local s = { }
    local n = 0
    for k, v in next, t do
        n = n + 1
        s[n] = k .. "=" .. v
    end
    if n == 0 then
        return ""
    elseif n == 1 then
        return s[1]
    else
        sort(s) -- costly but needed (occasional wrong hit otherwise)
        return concat(s,",")
    end
end

local function tabstr_mixed(t) -- indexed
    local s = { }
    local n = #t
    if n == 0 then
        return ""
    elseif n == 1 then
        local k = t[1]
        if k == true then
            return "++" -- we need to distinguish from "true"
        elseif k == false then
            return "--" -- we need to distinguish from "false"
        else
            return tostring(k) -- number or string
        end
    else
        for i=1,n do
            local k = t[i]
            if k == true then
                s[i] = "++" -- we need to distinguish from "true"
            elseif k == false then
                s[i] = "--" -- we need to distinguish from "false"
            else
                s[i] = k -- number or string
            end
        end
        return concat(s,",")
    end
end

local function tabstr_boolean(t)
    local s = { }
    local n = 0
    for k, v in next, t do
        n = n + 1
        if v then
            s[n] = k .. "+"
        else
            s[n] = k .. "-"
        end
    end
    if n == 0 then
        return ""
    elseif n == 1 then
        return s[1]
    else
        sort(s) -- costly but needed (occasional wrong hit otherwise)
        return concat(s,",")
    end
end

-- beware: we cannot unpack and repack the same table because then sharing
-- interferes (we could catch this if needed) .. so for now: save, reload
-- and repack in such cases (never needed anyway) .. a tricky aspect is that
-- we then need to sort more thanks to random hashing

function readers.pack(data)

    if data then

        local h, t, c = { }, { }, { }
        local hh, tt, cc = { }, { }, { }
        local nt, ntt = 0, 0

        local function pack_normal(v)
            local tag = tabstr_normal(v)
            local ht = h[tag]
            if ht then
                c[ht] = c[ht] + 1
                return ht
            else
                nt = nt + 1
                t[nt] = v
                h[tag] = nt
                c[nt] = 1
                return nt
            end
        end

        local function pack_flat(v)
            local tag = tabstr_flat(v)
            local ht = h[tag]
            if ht then
                c[ht] = c[ht] + 1
                return ht
            else
                nt = nt + 1
                t[nt] = v
                h[tag] = nt
                c[nt] = 1
                return nt
            end
        end

        local function pack_boolean(v)
            local tag = tabstr_boolean(v)
            local ht = h[tag]
            if ht then
                c[ht] = c[ht] + 1
                return ht
            else
                nt = nt + 1
                t[nt] = v
                h[tag] = nt
                c[nt] = 1
                return nt
            end
        end

        local function pack_indexed(v)
            local tag = concat(v," ")
            local ht = h[tag]
            if ht then
                c[ht] = c[ht] + 1
                return ht
            else
                nt = nt + 1
                t[nt] = v
                h[tag] = nt
                c[nt] = 1
                return nt
            end
        end

        local function pack_mixed(v)
            local tag = tabstr_mixed(v)
            local ht = h[tag]
            if ht then
                c[ht] = c[ht] + 1
                return ht
            else
                nt = nt + 1
                t[nt] = v
                h[tag] = nt
                c[nt] = 1
                return nt
            end
        end

        local function pack_final(v)
            -- v == number
            if c[v] <= criterium then
                return t[v]
            else
                -- compact hash
                local hv = hh[v]
                if hv then
                    return hv
                else
                    ntt = ntt + 1
                    tt[ntt] = t[v]
                    hh[v] = ntt
                    cc[ntt] = c[v]
                    return ntt
                end
            end
        end

        local function success(stage,pass)
            if nt == 0 then
                if trace_loading or trace_packing then
                    report_otf("pack quality: nothing to pack")
                end
                return false
            elseif nt >= threshold then
                local one, two, rest = 0, 0, 0
                if pass == 1 then
                    for k,v in next, c do
                        if v == 1 then
                            one = one + 1
                        elseif v == 2 then
                            two = two + 1
                        else
                            rest = rest + 1
                        end
                    end
                else
                    for k,v in next, cc do
                        if v > 20 then
                            rest = rest + 1
                        elseif v > 10 then
                            two = two + 1
                        else
                            one = one + 1
                        end
                    end
                    data.tables = tt
                end
                if trace_loading or trace_packing then
                    report_otf("pack quality: stage %s, pass %s, %s packed, 1-10:%s, 11-20:%s, rest:%s (criterium: %s)",
                        stage, pass, one+two+rest, one, two, rest, criterium)
                end
                return true
            else
                if trace_loading or trace_packing then
                    report_otf("pack quality: stage %s, pass %s, %s packed, aborting pack (threshold: %s)",
                        stage, pass, nt, threshold)
                end
                return false
            end
        end

        local function packers(pass)
            if pass == 1 then
                return pack_normal, pack_indexed, pack_flat, pack_boolean, pack_mixed
            else
                return pack_final, pack_final, pack_final, pack_final, pack_final
            end
        end

        local resources  = data.resources
        local sequences  = resources.sequences
        local sublookups = resources.sublookups
        local features   = resources.features

        local chardata     = characters and characters.data
        local descriptions = data.descriptions or data.glyphs

        if not descriptions then
            return
        end

        --

        for pass=1,2 do

            if trace_packing then
                report_otf("start packing: stage 1, pass %s",pass)
            end

            local pack_normal, pack_indexed, pack_flat, pack_boolean, pack_mixed = packers(pass)

            for unicode, description in next, descriptions do
                local boundingbox = description.boundingbox
                if boundingbox then
                    description.boundingbox = pack_indexed(boundingbox)
                end
                local math = description.math
                if math then
                    local kerns = math.kerns
                    if kerns then
                        for tag, kern in next, kerns do
                            kerns[tag] = pack_normal(kern)
                        end
                    end
                end
            end

            local function packthem(sequences)
                for i=1,#sequences do
                    local sequence = sequences[i]
                    local kind     = sequence.type
                    local steps    = sequence.steps
                    local order    = sequence.order
                    local features = sequence.features
                    local flags    = sequence.flags
                    if steps then
                        for i=1,#steps do
                            local step = steps[i]
                            if kind == "gpos_pair" then
                                local c = step.coverage
                                if c then
                                    if step.format == "kern" then
                                        for g1, d1 in next, c do
                                            c[g1] = pack_normal(d1)
                                        end
                                    else
                                        for g1, d1 in next, c do
                                            for g2, d2 in next, d1 do
                                                local f = d2[1] if f then d2[1] = pack_indexed(f) end
                                                local s = d2[2] if s then d2[2] = pack_indexed(s) end
                                            end
                                        end
                                    end
                                end
                            elseif kind == "gpos_single" then
                                local c = step.coverage
                                if c then
                                    if step.format == "kern" then
                                        step.coverage = pack_normal(c)
                                    else
                                        for g1, d1 in next, c do
                                            c[g1] = pack_indexed(d1)
                                        end
                                    end
                                end
                            elseif kind == "gpos_cursive" then
                                local c = step.coverage
                                if c then
                                    for g1, d1 in next, c do
                                        local f = d1[2] if f then d1[2] = pack_indexed(f) end
                                        local s = d1[3] if s then d1[3] = pack_indexed(s) end
                                    end
                                end
                            elseif kind == "gpos_mark2base" or kind == "gpos_mark2mark" then
                                local c = step.baseclasses
                                if c then
                                    for g1, d1 in next, c do
                                        for g2, d2 in next, d1 do
                                            d1[g2] = pack_indexed(d2)
                                        end
                                    end
                                end
                                local c = step.coverage
                                if c then
                                    for g1, d1 in next, c do
                                        d1[2] = pack_indexed(d1[2])
                                    end
                                end
                            elseif kind == "gpos_mark2ligature" then
                                local c = step.baseclasses
                                if c then
                                    for g1, d1 in next, c do
                                        for g2, d2 in next, d1 do
                                            for g3, d3 in next, d2 do
                                                d2[g3] = pack_indexed(d3)
                                            end
                                        end
                                    end
                                end
                                local c = step.coverage
                                if c then
                                    for g1, d1 in next, c do
                                        d1[2] = pack_indexed(d1[2])
                                    end
                                end
                            end
                            -- if ... chain ...
                            local rules = step.rules
                            if rules then
                                for i=1,#rules do
                                    local rule = rules[i]
                                    local r = rule.before       if r then for i=1,#r do r[i] = pack_boolean(r[i]) end end
                                    local r = rule.after        if r then for i=1,#r do r[i] = pack_boolean(r[i]) end end
                                    local r = rule.current      if r then for i=1,#r do r[i] = pack_boolean(r[i]) end end
                                    local r = rule.replacements if r then rule.replacements  = pack_flat   (r)    end -- can have holes
                                end
                            end
                        end
                    end
                    if order then
                        sequence.order = pack_indexed(order)
                    end
                    if features then
                        for script, feature in next, features do
                            features[script] = pack_normal(feature)
                        end
                    end
                    if flags then
                        sequence.flags = pack_normal(flags)
                    end
               end
            end

            if sequences then
                packthem(sequences)
            end

            if sublookups then
                packthem(sublookups)
            end

            if features then
                for k, list in next, features do
                    for feature, spec in next, list do
                        list[feature] = pack_normal(spec)
                    end
                end
            end

            if not success(1,pass) then
                return
            end

        end

        if nt > 0 then

            for pass=1,2 do

                if trace_packing then
                    report_otf("start packing: stage 2, pass %s",pass)
                end

                local pack_normal, pack_indexed, pack_flat, pack_boolean, pack_mixed = packers(pass)

                for unicode, description in next, descriptions do
                    local math = description.math
                    if math then
                        local kerns = math.kerns
                        if kerns then
                            math.kerns = pack_normal(kerns)
                        end
                    end
                end

                local function packthem(sequences)
                    for i=1,#sequences do
                        local sequence = sequences[i]
                        local kind     = sequence.type
                        local steps    = sequence.steps
                        local features = sequence.features
                        if steps then
                            for i=1,#steps do
                                local step = steps[i]
                                if kind == "gpos_pair" then
                                    local c = step.coverage
                                    if c then
                                        if step.format == "kern" then
                                            -- todo !
                                        else
                                            for g1, d1 in next, c do
                                                for g2, d2 in next, d1 do
                                                    d1[g2] = pack_normal(d2)
                                                end
                                            end
                                        end
                                    end
--                                 elseif kind == "gpos_mark2base" or kind == "gpos_mark2mark" or kind == "gpos_mark2ligature" then
-- local c = step.baseclasses
-- for k, v in next, c do
--     c[k] = pack_normal(v)
-- end
                                end
                                local rules = step.rules
                                if rules then
                                    for i=1,#rules do
                                        local rule = rules[i]
                                        local r = rule.before  if r then rule.before  = pack_normal(r) end
                                        local r = rule.after   if r then rule.after   = pack_normal(r) end
                                        local r = rule.current if r then rule.current = pack_normal(r) end
                                    end
                                end
                            end
                        end
                        if features then
                            sequence.features = pack_normal(features)
                        end
                   end
                end
                if sequences then
                    packthem(sequences)
                end
                if sublookups then
                    packthem(sublookups)
                end
                -- features
                if not success(2,pass) then
                 -- return
                end
            end

            for pass=1,2 do
                if trace_packing then
                    report_otf("start packing: stage 3, pass %s",pass)
                end

                local pack_normal, pack_indexed, pack_flat, pack_boolean, pack_mixed = packers(pass)

                local function packthem(sequences)
                    for i=1,#sequences do
                        local sequence = sequences[i]
                        local kind     = sequence.type
                        local steps    = sequence.steps
                        local features = sequence.features
                        if steps then
                            for i=1,#steps do
                                local step = steps[i]
                                if kind == "gpos_pair" then
                                    local c = step.coverage
                                    if c then
                                        if step.format == "kern" then
                                            -- todo !
                                        else
                                            for g1, d1 in next, c do
                                                c[g1] = pack_normal(d1)
                                            end
                                        end
                                    end
                                end
                            end
                        end
                   end
                end

                if sequences then
                    packthem(sequences)
                end
                if sublookups then
                    packthem(sublookups)
                end

            end

        end

    end
end

local unpacked_mt = {
    __index =
        function(t,k)
            t[k] = false
            return k -- next time true
        end
}

function readers.unpack(data)

    if data then
        local tables = data.tables
        if tables then
            local resources    = data.resources
            local descriptions = data.descriptions or data.glyphs
            local sequences    = resources.sequences
            local sublookups   = resources.sublookups
            local features     = resources.features
            local unpacked     = { }
            setmetatable(unpacked,unpacked_mt)
            for unicode, description in next, descriptions do
                local tv = tables[description.boundingbox]
                if tv then
                    description.boundingbox = tv
                end
                local math = description.math
                if math then
                    local kerns = math.kerns
                    if kerns then
                        local tm = tables[kerns]
                        if tm then
                            math.kerns = tm
                            kerns = unpacked[tm]
                        end
                        if kerns then
                            for k, kern in next, kerns do
                                local tv = tables[kern]
                                if tv then
                                    kerns[k] = tv
                                end
                            end
                        end
                    end
                end
            end

            local function unpackthem(sequences)
                for i=1,#sequences do
                    local sequence  = sequences[i]
                    local kind      = sequence.type
                    local steps     = sequence.steps
                    local order     = sequence.order
                    local features  = sequence.features
                    local flags     = sequence.flags
                    local markclass = sequence.markclass
                    if steps then
                        for i=1,#steps do
                            local step = steps[i]
                            if kind == "gpos_pair" then
                                local c = step.coverage
                                if c then
                                    if step.format == "kern" then
                                        for g1, d1 in next, c do
                                            local tv = tables[d1]
                                            if tv then
                                                c[g1] = tv
                                            end
                                        end
                                    else
                                        for g1, d1 in next, c do
                                            local tv = tables[d1]
                                            if tv then
                                                c[g1] = tv
                                                d1 = tv
                                            end
                                            for g2, d2 in next, d1 do
                                                local tv = tables[d2]
                                                if tv then
                                                    d1[g2] = tv
                                                    d2 = tv
                                                end
                                                local f = tables[d2[1]] if f then d2[1] = f end
                                                local s = tables[d2[2]] if s then d2[2] = s end
                                            end
                                        end
                                    end
                                end
                            elseif kind == "gpos_single" then
                                local c = step.coverage
                                if c then
                                    if step.format == "kern" then
                                        local tv = tables[c]
                                        if tv then
                                            step.coverage = tv
                                        end
                                    else
                                        for g1, d1 in next, c do
                                            local tv = tables[d1]
                                            if tv then
                                                c[g1] = tv
                                            end
                                        end
                                    end
                                end
                            elseif kind == "gpos_cursive" then
                                local c = step.coverage
                                if c then
                                    for g1, d1 in next, c do
                                        local f = tables[d1[2]] if f then d1[2] = f end
                                        local s = tables[d1[3]] if s then d1[3] = s end
                                    end
                                end
                            elseif kind == "gpos_mark2base" or kind == "gpos_mark2mark" then
                                local c = step.baseclasses
                                if c then
-- for k, v in next, c do
--     local tv = tables[v]
--     if tv then
--         c[k] = tv
--     end
-- end
                                    for g1, d1 in next, c do
                                        for g2, d2 in next, d1 do
                                            local tv = tables[d2]
                                            if tv then
                                                d1[g2] = tv
                                            end
                                        end
                                    end
                                end
                                local c = step.coverage
                                if c then
                                    for g1, d1 in next, c do
                                        local tv = tables[d1[2]]
                                        if tv then
                                            d1[2] = tv
                                        end
                                    end
                                end
                            elseif kind == "gpos_mark2ligature" then
                                local c = step.baseclasses
                                if c then
-- for k, v in next, c do
--     local tv = tables[v]
--     if tv then
--         c[k] = tv
--     end
-- end
                                    for g1, d1 in next, c do
                                        for g2, d2 in next, d1 do
                                            for g3, d3 in next, d2 do
                                                local tv = tables[d2[g3]]
                                                if tv then
                                                    d2[g3] = tv
                                                end
                                            end
                                        end
                                    end
                                end
                                local c = step.coverage
                                if c then
                                    for g1, d1 in next, c do
                                        local tv = tables[d1[2]]
                                        if tv then
                                            d1[2] = tv
                                        end
                                    end
                                end
                            end
                            local rules = step.rules
                            if rules then
                                for i=1,#rules do
                                    local rule = rules[i]
                                    local before = rule.before
                                    if before then
                                        local tv = tables[before]
                                        if tv then
                                            rule.before = tv
                                            before = tv
                                        end
                                        for i=1,#before do
                                            local tv = tables[before[i]]
                                            if tv then
                                                before[i] = tv
                                            end
                                        end
                                    end
                                    local after = rule.after
                                    if after then
                                        local tv = tables[after]
                                        if tv then
                                            rule.after = tv
                                            after = tv
                                        end
                                        for i=1,#after do
                                            local tv = tables[after[i]]
                                            if tv then
                                                after[i] = tv
                                            end
                                        end
                                    end
                                    local current = rule.current
                                    if current then
                                        local tv = tables[current]
                                        if tv then
                                            rule.current = tv
                                            current = tv
                                        end
                                        for i=1,#current do
                                            local tv = tables[current[i]]
                                            if tv then
                                                current[i] = tv
                                            end
                                        end
                                    end
                                    local replacements = rule.replacements
                                    if replacements then
                                        local tv = tables[replace]
                                        if tv then
                                            rule.replacements = tv
                                        end
                                    end
                                end
                            end
                        end
                    end
                    if features then
                        local tv = tables[features]
                        if tv then
                            sequence.features = tv
                            features = tv
                        end
                        for script, feature in next, features do
                            local tv = tables[feature]
                            if tv then
                                features[script] = tv
                            end
                        end
                    end
                    if order then
                        local tv = tables[order]
                        if tv then
                            sequence.order = tv
                        end
                    end
                    if flags then
                        local tv = tables[flags]
                        if tv then
                            sequence.flags = tv
                        end
                    end
               end
            end

            if sequences then
                unpackthem(sequences)
            end

            if sublookups then
                unpackthem(sublookups)
            end

            if features then
                for k, list in next, features do
                    for feature, spec in next, list do
                        local tv = tables[spec]
                        if tv then
                            list[feature] = tv
                        end
                    end
                end
            end

            data.tables = nil
        end
    end
end

local mt = {
    __index = function(t,k) -- maybe set it
        if k == "height" then
            local ht = t.boundingbox[4]
            return ht < 0 and 0 or ht
        elseif k == "depth" then
            local dp = -t.boundingbox[2]
            return dp < 0 and 0 or dp
        elseif k == "width" then
            return 0
        elseif k == "name" then -- or maybe uni*
            return forcenotdef and ".notdef"
        end
    end
}

local function sameformat(sequence,steps,first,nofsteps,kind)
    return true
end

local function mergesteps_1(lookup,strict)
    local steps    = lookup.steps
    local nofsteps = lookup.nofsteps
    local first    = steps[1]
    if strict then
        local f = first.format
        for i=2,nofsteps do
            if steps[i].format ~= f then
                report("not merging %a steps of %a lookup %a, different formats",nofsteps,lookup.type,lookup.name)
                return 0
            end
        end
    end
    report("merging %a steps of %a lookup %a",nofsteps,lookup.type,lookup.name)
    local target = first.coverage
    for i=2,nofsteps do
        for k, v in next, steps[i].coverage do
            if not target[k] then
                target[k] = v
            end
        end
    end
    lookup.nofsteps = 1
    lookup.merged   = true
    lookup.steps    = { first }
    return nofsteps - 1
end


local function mergesteps_2(lookup,strict) -- pairs
    local steps    = lookup.steps
    local nofsteps = lookup.nofsteps
    local first    = steps[1]
    if strict then
        local f = first.format
        for i=2,nofsteps do
            if steps[i].format ~= f then
                report("not merging %a steps of %a lookup %a, different formats",nofsteps,lookup.type,lookup.name)
                return 0
            end
        end
    end
    report("merging %a steps of %a lookup %a",nofsteps,lookup.type,lookup.name)
    local target = first.coverage
    for i=2,nofsteps do
        for k, v in next, steps[i].coverage do
            local tk = target[k]
            if tk then
                for k, v in next, v do
                    if not tk[k] then
                        tk[k] = v
                    end
                end
            else
                target[k] = v
            end
        end
    end
    lookup.nofsteps = 1
    lookup.steps = { first }
    return nofsteps - 1
end


local function mergesteps_3(lookup,strict) -- marks
    local steps    = lookup.steps
    local nofsteps = lookup.nofsteps
    local first    = steps[1]
    report("merging %a steps of %a lookup %a",nofsteps,lookup.type,lookup.name)
    local baseclasses = { }
    local coverage    = { }
    local used        = { }
    for i=1,nofsteps do
        local offset = i*10
        local step   = steps[i]
        for k, v in sortedhash(step.baseclasses) do
            baseclasses[offset+k] = v
        end
        for k, v in next, step.coverage do
            local tk = coverage[k]
            if tk then
                for k, v in next, v do
                    if not tk[k] then
                        tk[k] = v
                        local c = offset + v[1]
                        v[1] = c
                        if not used[c] then
                            used[c] = true
                        end
                    end
                end
            else
                coverage[k] = v
                local c = offset + v[1]
                v[1] = c
                if not used[c] then
                    used[c] = true
                end
            end
        end
    end
    for k, v in next, baseclasses do
        if not used[k] then
            baseclasses[k] = nil
            report("discarding not used baseclass %i",k)
        end
    end
    first.baseclasses = baseclasses
    first.coverage    = coverage
    lookup.nofsteps   = 1
    lookup.steps      = { first }
    return nofsteps - 1
end

local function nested(old,new)
    for k, v in next, old do
        if k == "ligature" then
            if not new.ligature then
                new.ligature = v
            end
        else
            local n = new[k]
            if n then
                nested(v,n)
            else
                new[k] = v
            end
        end
    end
end

local function mergesteps_4(lookup) -- ligatures
    local steps    = lookup.steps
    local nofsteps = lookup.nofsteps
    local first    = steps[1]
    report("merging %a steps of %a lookup %a",nofsteps,lookup.type,lookup.name)
    local target = first.coverage
    for i=2,nofsteps do
        for k, v in next, steps[i].coverage do
            local tk = target[k]
            if tk then
                nested(v,tk)
            else
                target[k] = v
            end
        end
    end
    lookup.nofsteps = 1
    lookup.steps = { first }
    return nofsteps - 1
end

local function checkkerns(lookup)
    local steps    = lookup.steps
    local nofsteps = lookup.nofsteps
    for i=1,nofsteps do
        local step = steps[i]
        if step.format == "pair" then
            local coverage = step.coverage
            local kerns    = true
            for g1, d1 in next, coverage do
                if d1[1] ~= 0 or d1[2] ~= 0 or d1[4] ~= 0 then
                    kerns = false
                    break
                end
            end
            if kerns then
                report("turning pairs of step %a of %a lookup %a into kerns",i,lookup.type,lookup.name)
                for g1, d1 in next, coverage do
                    coverage[g1] = d1[3]
                end
                step.format = "kern"
            end
        end
    end
end

local function checkpairs(lookup)
    local steps    = lookup.steps
    local nofsteps = lookup.nofsteps
    local kerned   = 0
    for i=1,nofsteps do
        local step = steps[i]
        if step.format == "pair" then
            local coverage = step.coverage
            local kerns    = true
            for g1, d1 in next, coverage do
                for g2, d2 in next, d1 do
                    if d2[2] then
                        kerns = false
                        break
                    else
                        local v = d2[1]
                        if v[1] ~= 0 or v[2] ~= 0 or v[4] ~= 0 then
                            kerns = false
                            break
                        end
                    end
                end
            end
            if kerns then
                report("turning pairs of step %a of %a lookup %a into kerns",i,lookup.type,lookup.name)
                for g1, d1 in next, coverage do
                    for g2, d2 in next, d1 do
                        d1[g2] = d2[1][3]
                    end
                end
                step.format = "kern"
                kerned = kerned + 1
            end
        end
    end
    return kerned
end

function readers.compact(data)
    if not data or data.compacted then
        return
    else
        data.compacted = true
    end
    local resources = data.resources
    local merged    = 0
    local kerned    = 0
    local allsteps  = 0
    local function compact(what)
        local lookups = resources[what]
        if lookups then
            for i=1,#lookups do
                local lookup   = lookups[i]
                local nofsteps = lookup.nofsteps
                allsteps = allsteps + nofsteps
                if nofsteps > 1 then
                    local kind = lookup.type
                    if kind == "gsub_single" or kind == "gsub_alternate" or kind == "gsub_multiple" then
                        merged = merged + mergesteps_1(lookup)
                    elseif kind == "gsub_ligature" then
                        merged = merged + mergesteps_4(lookup)
                    elseif kind == "gpos_single" then
                        merged = merged + mergesteps_1(lookup,true)
                        checkkerns(lookup)
                    elseif kind == "gpos_pair" then
                        merged = merged + mergesteps_2(lookup,true)
                        kerned = kerned + checkpairs(lookup)
                    elseif kind == "gpos_cursive" then
                        merged = merged + mergesteps_2(lookup)
                    elseif kind == "gpos_mark2mark" or kind == "gpos_mark2base" or kind == "gpos_mark2ligature" then
                        merged = merged + mergesteps_3(lookup)
                    end
                end
            end
        else
            report("no lookups in %a",what)
        end
    end
    compact("sequences")
    compact("sublookups")
    if merged > 0 then
        report("%i steps of %i removed due to merging",merged,allsteps)
    end
    if kerned > 0 then
        report("%i steps of %i steps turned from pairs into kerns",kerned,allsteps)
    end
end

function readers.expand(data)
    if not data or data.expanded then
        return
    else
        data.expanded = true
    end
    local resources    = data.resources
    local sublookups   = resources.sublookups
    local sequences    = resources.sequences -- were one level up
    local markclasses  = resources.markclasses
    local descriptions = data.descriptions
    if descriptions then
        local defaultwidth  = resources.defaultwidth  or 0
        local defaultheight = resources.defaultheight or 0
        local defaultdepth  = resources.defaultdepth  or 0
        local basename      = trace_markwidth and file.basename(resources.filename)
        for u, d in next, descriptions do
            local bb = d.boundingbox
            local wd = d.width
            if not wd then
                -- or bb?
                d.width = defaultwidth
            elseif trace_markwidth and wd ~= 0 and d.class == "mark" then
                report("mark %a with width %b found in %a",d.name or "<noname>",wd,basename)
            end
            if bb then
                local ht =  bb[4]
                local dp = -bb[2]
                if ht == 0 or ht < 0 then
                    -- not set
                else
                    d.height = ht
                end
                if dp == 0 or dp < 0 then
                    -- not set
                else
                    d.depth  = dp
                end
            end
        end
    end
    local function expandlookups(sequences)
        if sequences then
            -- we also need to do sublookups
            for i=1,#sequences do
                local sequence = sequences[i]
                local steps    = sequence.steps
                if steps then
                    local kind = sequence.type
                    local markclass = sequence.markclass
                    if markclass then
                        if not markclasses then
                            report_warning("missing markclasses")
                            sequence.markclass = false
                        else
                            sequence.markclass = markclasses[markclass]
                        end
                    end
                    for i=1,sequence.nofsteps do
                        local step = steps[i]
                        local baseclasses = step.baseclasses
                        if baseclasses then
                            local coverage = step.coverage
                            for k, v in next, coverage do
                                v[1] = baseclasses[v[1]] -- slot 1 is a placeholder
                            end
                        elseif kind == "gpos_cursive" then
                            local coverage = step.coverage
                            for k, v in next, coverage do
                                v[1] = coverage -- slot 1 is a placeholder
                            end
                        end
                        local rules = step.rules
                        if rules then
                            local rulehash   = { }
                            local rulesize   = 0
                            local coverage   = { }
                            local lookuptype = sequence.type
                            step.coverage    = coverage -- combined hits
                            for nofrules=1,#rules do
                                local rule         = rules[nofrules]
                                local current      = rule.current
                                local before       = rule.before
                                local after        = rule.after
                                local replacements = rule.replacements or false
                                local sequence     = { }
                                local nofsequences = 0
                                if before then
                                    for n=1,#before do
                                        nofsequences = nofsequences + 1
                                        sequence[nofsequences] = before[n]
                                    end
                                end
                                local start = nofsequences + 1
                                for n=1,#current do
                                    nofsequences = nofsequences + 1
                                    sequence[nofsequences] = current[n]
                                end
                                local stop = nofsequences
                                if after then
                                    for n=1,#after do
                                        nofsequences = nofsequences + 1
                                        sequence[nofsequences] = after[n]
                                    end
                                end
                                local lookups = rule.lookups or false
                                local subtype = nil
                                if lookups then
                                    for k, v in next, lookups do
                                        local lookup = sublookups[v]
                                        if lookup then
                                            lookups[k] = lookup
                                            if not subtype then
                                                subtype = lookup.type
                                            end
                                        else
                                            -- already expanded
                                        end
                                    end
                                end
                                if sequence[1] then -- we merge coverage into one
                                    rulesize = rulesize + 1
                                    rulehash[rulesize] = {
                                        nofrules,     -- 1
                                        lookuptype,   -- 2
                                        sequence,     -- 3
                                        start,        -- 4
                                        stop,         -- 5
                                        lookups,      -- 6 (6/7 also signal of what to do)
                                        replacements, -- 7
                                        subtype,      -- 8
                                    }
                                    for unic in next, sequence[start] do
                                        local cu = coverage[unic]
                                        if not cu then
                                            coverage[unic] = rulehash -- can now be done cleaner i think
                                        end
                                    end
                                end
                            end
                        end
                    end
                end
            end
        end
    end
    expandlookups(sequences)
    expandlookups(sublookups)
end