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

=begin COPYRIGHT

----------------------------------------------------------------------------

    Copyright (C) 2005-2021 Marc Penninga.

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation, either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to
        Free Software Foundation, Inc.,
        59 Temple Place,
        Suite 330,
        Boston, MA 02111-1307,
        USA

----------------------------------------------------------------------------

=end COPYRIGHT

=cut

use strict;
use warnings;

use Cwd ();
use File::Basename ();
use File::Path ();
use File::Spec ();
use Getopt::Long ();
use Pod::Usage ();
use POSIX ();

my $VERSION = '20210401';

my ($d, $m, $y) = (localtime time)[3 .. 5];
my $TODAY = sprintf "%04d/%02d/%02d", $y + 1900, $m + 1, $d;

my $RUNNING_AS_MAIN = (__PACKAGE__ eq 'main');


=begin Comment

----------------------------------------------------------------------------

    Autoinst consists of a number of parts:

        main        Contains just the main() routine.

        Options     Parses the command-line options.
                    Note that the *processing* of the user's choices
                    is mostly taken care of by the `Tables` package,
                    since this processing involves adapting those tables.

        Log         Logs the font parsing and creation process.

        Attr        Contains tables and routines that represent
                    font attributes (weight, width, shape).

        Font        Parses an OpenType font's metadata.

        Tables      Contains tables that drive the font creation process
                    (especially the decisions which fonts to create).

        Work        Generates all font files, driven by data from `Tables`.

        LaTeX       Creates LaTeX support (.sty and .fd files).

        Otftotfm    Drives `otftotfm` to actually generate the fonts.

        Util        Some miscellaneous utility functions.

----------------------------------------------------------------------------

=end Comment

=cut


sub main {
    print "autoinst, version $VERSION\n";

    Options::parse_options();
    Tables::process_options();

    my %fontfamily;
    for my $fontfile (@ARGV) {
        my $font = Font::parse($fontfile);
        my $family = $font->{family};
        push @{$fontfamily{$family}}, $font;
    }

    while (my ($family, $fontlist) = each %fontfamily) {

        local %ARGV = %ARGV;
        Tables::process_family_dependent_options($fontlist);

        my $log = Log->new($ARGV{logfile});
        $log->log_options();
        $log->log_parsing($fontlist);

        # We defer asserting that all fonts were parsed in a unique way
        # until after the results of the parsing have been logged.
        Font::assert_unique($log, $fontlist);

        my $mappings = Attr::map_nfss_codes($fontlist);
        my ($from_nfss, $to_nfss) = @{$mappings};
        $log->log_nfss_mapping($from_nfss);

        my @workitems = Work::generate_worklist($fontlist);
        $log->log_worklist(\@workitems);

        my $targetdirs = Otftotfm::get_targetdirs($family, $fontlist);
        my @commands = map { Otftotfm::create_command($_, $targetdirs) }
                           @workitems;
        $log->log_commands(\@commands) if $ARGV{verbose} >= 1;

        if (!$ARGV{dryrun}) {
            LaTeX::create_support_files(\@workitems, $family, $to_nfss);
            Otftotfm::run_commands(\@commands, $family, $log);

            if ($ARGV{t1suffix}) {
                Work::modify_fontnames($family, $fontlist);
            }

            print <<"END_MESSAGE_UPDMAP";
[INFO]      Done generating fonts!
            Please update TeX's databases (by calling 'texhash' and 'updmap'
            or their equivalents on your system) before using these fonts.
END_MESSAGE_UPDMAP
        }

        $log->close();
    }

    return;
}


############################################################################


package Attr;

=begin Comment

    Some fontnames contain abbreviated words for width, weight and/or shape;
    we unabbreviate these using the following table.

=end Comment

=cut

my %FULL_FORM = (
    cmp     =>  'compressed',
    comp    =>  'compressed',
    cond    =>  'condensed',
    demi    =>  'demibold',
    extcond =>  'extracondensed',
    hair    =>  'hairline',
    incline =>  'inclined',
    it      =>  'italic',
    ita     =>  'italic',
    md      =>  'medium',
    slant   =>  'slanted',
    ultra   =>  'ultrablack',
);

# Auxiliary table that reverses FULL_FORM; maps full forms to abbrevs.
my %abbrev;
while (my ($k, $v) = each %FULL_FORM) {
    push @{$abbrev{$v}}, $k;
}

# Add full forms as known abbreviations of themselves.
for my $full (keys %abbrev) {
    push @{$abbrev{$full}}, $full;
}

# Internal helper: returns a list of known abbreviations of its argument.
sub _get_abbreviated_forms {
    my $key = shift;

    return @{ $abbrev{$key} // [$key] };
}


=begin Comment

    LaTeX's NFSS contains a number of standard codes for weight and width:
    - weight: ul, el, l, sl, m, sb, b, eb, ub
    - width:  uc, ec, c, sc, m, sx, x, ex, ux

    These codes are not always a perfect match with the weights and widths
    present in a font family; some families (especially many sans serif ones)
    contain more or different weights and widths, and the naming of those
    weights and widths isn't always consistent between font families.
    To handle this situation, we use a two-tiered approach:
    1.  We install all fonts using a "series" name that is the concatenation
        of whatever the font designer has chosen to call the weight and width
        (but in all *lower*case).
    2.  We add "alias" rules to the .fd files that map the standard NFSS codes
        to actual fonts.

    In step 1, we follow NFSS in leaving out any occurrence of
    the word "regular" unless *both* weight and width are Regular;
    in that case, the 'series' attribute becomes "regular".

    The two tables WEIGHT and WIDTH are used to control step 2.
    It contains several entries of the form

        sc  =>  [ qw( semicondensed narrow ) ],

    This should be read as follows: the NFSS code "sc" is mapped to
    the *first* width on the right hand side present in the current family.

    Please note that the tables contain empty keys instead of "m" for the
    regular weight and width. NFSS actually combines weight and width into
    a single "series" attribute; a weight or width of "m" is left out of
    this combination (unless *both* weight and width are equal to "m"; then
    the series becomes "m", but that's a special case we deal with later on).

    In addition to the mapping of NFSS codes, the two mentioned tables are
    also used in parsing the font's metadata to determine its weight and
    width: any string that occurs on the right hand side is considered a
    possible name to be searched for.

    These tables can be extended to teach autoinst about new weights or
    widths.  Suppose your font family contains a "Hemibold" weight, that
    you want mapped to the "sb" code. Then add the name "hemibold" to
    the right hand side of the "sb" entry in the WEIGHT table:

        sb  =>  [ qw( semibold demibold medium hemibold ) ],

    In this case, since it's in last position, it's only mapped to "sb"
    if none of the other fonts are present. Put it earlier in the list
    to give it higher priority.

    Note that autoinst converts all metadata to lowercase to avoid
    inconsistent capitalization; so all entries in these tables should
    be *lowercase* as well.

    Technical notes:
    -   We define WEIGHT and WIDTH first as arrays
        and then as hashtables; this allows us to use the array-variants
        as an *ordered* (by weight/width) list of values (in the routines
        get_all_nfss_weights and get_all_nfss_widths).

=end Comment

=cut

my @WEIGHT = (
    ul  =>  [ qw( ultralight thin 100 hairline ) ],
    el  =>  [ qw( extralight 200 ) ],
    l   =>  [ qw( light 300 ) ],
    sl  =>  [ qw( semilight blond ) ],
    ''  =>  [ qw( regular normal text book 400 normallight normaldark ) ],
    sb  =>  [ qw( semibold demibold 600 medium 500 ) ],
    b   =>  [ qw( bold 700 ) ],
    eb  =>  [ qw( extrabold 800 ) ],
    ub  =>  [ qw( ultrabold black heavy extrablack ultrablack 900 fatface
                  ultraheavy poster super 1000 ) ],
);

my @WIDTH = (
    uc  =>  [ qw( ultracondensed extracompressed ultracompressed ) ],
    ec  =>  [ qw( extracondensed compressed compact ) ],
    c   =>  [ qw( condensed ) ],
    sc  =>  [ qw( semicondensed narrow ) ],
    ''  =>  [ qw( regular ) ],
    sx  =>  [ qw( semiextended semiexpanded wide ) ],
    x   =>  [ qw( extended expanded ) ],
    ex  =>  [],
    ux  =>  [],
);

my %WEIGHT = @WEIGHT;
@WEIGHT = grep { !ref } @WEIGHT;
# Add abbreviated forms of weight names.
for my $code (@WEIGHT) {
    $WEIGHT{$code}
        = [ map { _get_abbreviated_forms($_) } @{$WEIGHT{$code}} ];
}

my @allweights = grep { $_ !~ m/ medium | regular | text /xms }
                      map { @{$_} } values %WEIGHT;
@allweights = (
    Util::sort_desc_length(@allweights),
    qw(medium regular text)
);


my %WIDTH = @WIDTH;
@WIDTH = grep { !ref } @WIDTH;
# Add abbreviated forms.
for my $code (@WIDTH) {
    $WIDTH{$code}
        = [ map { _get_abbreviated_forms($_) } @{$WIDTH{$code}} ];
}

my @allwidths = grep { $_ ne 'regular' } map { @{$_} } values %WIDTH;
@allwidths = Util::sort_desc_length(@allwidths);


=begin Comment

    The SHAPE table maps various shape names to NFSS codes.

    Like in the other * tables, entries may be added to teach autoinst
    about new shapes. Note that this table is "the other way around"
    compared to WEIGHT and WIDTH; those map NFSS codes to names,
    this one maps names to NFSS codes. That's because the data from
    this table is used in a slightly different way; notably, it isn't
    used in the map_nfss_codes routine.

=end Comment

=cut

my %SHAPE = (
    roman       =>  'n',
    upright     =>  'n',
    italic      =>  'it',
    inclined    =>  'sl',
    oblique     =>  'sl',
    slanted     =>  'sl',
    romani      =>  'n',    # Silentium has two roman shapes, but no italic;
    romanii     =>  'it',   # so we cheat by mapping the second roman to 'it'
);

# Add abbreviated forms.
for my $full (keys %abbrev) {
    if (defined $SHAPE{$full}) {
        for my $abbrev (_get_abbreviated_forms($full)) {
            $SHAPE{$abbrev} = $SHAPE{$full};
        }
    }
}

my @allshapes = Util::sort_desc_length(keys %SHAPE);


# --------------------------------------------------------------------------
#   Returns the unabbreviated form of its argument,
#   or its argument itself if no unabbreviated form is known.
# --------------------------------------------------------------------------
sub unabbreviate {
    my $key = shift;

    return $FULL_FORM{$key} // $key;
}


# --------------------------------------------------------------------------
#   Prepends weight names to the WEIGHT table for a given NFSS code.
# --------------------------------------------------------------------------
sub set_weight {
    my ($key, @values) = @_;

    $WEIGHT{$key} = [ @values, @{$WEIGHT{$key}} ];
    return;
}


# --------------------------------------------------------------------------
#   Returns a list of NFSS weight names, sorted by weight.
# --------------------------------------------------------------------------
sub get_all_nfss_weights {
    return @WEIGHT;
}


# --------------------------------------------------------------------------
#   Returns a list of all known weights, in an order suitable for searching.
# --------------------------------------------------------------------------
sub get_all_weights {
    return @allweights;
}


# --------------------------------------------------------------------------
#   Prepends weight names to the WIDTH table for a given NFSS code.
# --------------------------------------------------------------------------
sub set_width {
    my ($key, @values) = @_;

    $WIDTH{$key} = [ @values, @{$WIDTH{$key}} ];
    return;
}


# --------------------------------------------------------------------------
#   Returns a list of NFSS width names, sorted by width.
# --------------------------------------------------------------------------
sub get_all_nfss_widths {
    return @WIDTH;
}


# --------------------------------------------------------------------------
#   Returns a list of all known widths, in an order suitable for searching.
# --------------------------------------------------------------------------
sub get_all_widths {
    return @allwidths;
}


# --------------------------------------------------------------------------
#   Returns the NFSS code for the given shape.
# --------------------------------------------------------------------------
sub to_nfss {
    my $key = shift;

    return $SHAPE{$key};
}


# --------------------------------------------------------------------------
#   Returns a list of all known shapes, in an order suitable for searching.
# --------------------------------------------------------------------------
sub get_all_shapes {
    return @allshapes;
}


# --------------------------------------------------------------------------
#   Returns mappings of NFSS codes to weight and width, and vice versa.
# --------------------------------------------------------------------------
sub map_nfss_codes {
    my $fontlist = shift;

    my (%weight, %width);
    for my $font (@{$fontlist}) {
        $weight{ $font->{weight} } //= $font->{weight_class};
        $width{  $font->{width} }  //= $font->{width_class};
    }

    my $from_nfss = {
        weight => {},
        width => {},
    };

    for my $nfssweight (get_all_nfss_weights()) {
        $from_nfss->{weight}{$nfssweight}
            = [ grep { $weight{$_} } @{$WEIGHT{$nfssweight}} ];
    }

    # Some trickery to handle the case where the ul/ub codes are mapped
    # but the el/eb codes are still empty. We try two things:
    # 1.  if there is a Thin (Heavy) weight and this is less extreme
    #     than the weight mapped to ul (ub), we map Thin (Heavy) to ul (ub)
    # 2.  otherwise we move the ul/ub weight to the el/eb position,
    #     unless that weight is the Ultralight/Ultrabold weight
    if (!$ARGV{el} and !$ARGV{ul}) {
        if (@{$from_nfss->{weight}{ul}}
                and !@{$from_nfss->{weight}{el}}) {
            if ($weight{thin}
                    and $weight{thin}
                        > $weight{$from_nfss->{weight}{ul}[0]}) {
                $from_nfss->{weight}{el} = ['thin',];
            }
            elsif ($from_nfss->{weight}{ul}[0] ne 'ultralight') {
                $from_nfss->{weight}{el}
                    = [ shift @{$from_nfss->{weight}{ul}} ];
            }
        }
    }
    if (!$ARGV{eb} and !$ARGV{ub}) {
        if (@{$from_nfss->{weight}{ub}}
                and !@{$from_nfss->{weight}{eb}}) {
            if ($weight{heavy}
                    and $weight{heavy}
                        < $weight{$from_nfss->{weight}{ub}[0]}) {
                $from_nfss->{weight}{eb} = ['heavy',]
                    unless @{$from_nfss->{weight}{b}}
                       and $weight{$from_nfss->{weight}{b}[0]}
                           > $weight{heavy};
            }
            elsif ($from_nfss->{weight}{ub}[0] ne 'ultrabold') {
                $from_nfss->{weight}{eb}
                    = [ shift @{$from_nfss->{weight}{ub}} ];
            }
        }
    }

    # Special case: if we don't have Regular but we *do* have Medium,
    # move Medium from the "sb" list to the "m" (i.e., Regular) one.
    if (!@{$from_nfss->{weight}{''}}) {
        my $alternate = ( grep { $weight{$_} } qw(medium 500) )[0];
        if ($alternate) {
            $from_nfss->{weight}{''} = [$alternate];
            $from_nfss->{weight}{sb}
                = [ grep { $_ ne $alternate } @{$from_nfss->{weight}{sb}} ];
        }
    }

    # Some more trickery to map the sl code to Book or Text (but of course
    # only if sl is empty and Book/Text is lighter than Regular)
    if (!@{$from_nfss->{weight}{sl}}) {
        $from_nfss->{weight}{sl}
            = [ grep { $weight{$_} < $weight{$from_nfss->{weight}{''}[0]} }
                     @{$from_nfss->{weight}{''}} ];
    }

    NFSSWIDTH:
    for my $nfsswidth (get_all_nfss_widths()) {
        for my $width ( @{$WIDTH{$nfsswidth}} ) {
            if ($width{$width}) {
                $from_nfss->{width}{$nfsswidth} = [$width];
                next NFSSWIDTH;
            }
        }
        $from_nfss->{width}{$nfsswidth} = [];
    }

    # Reverse the %from_nfss mapping to get %to_nfss
    my %to_nfss;
    NFSSWEIGHT:
    for my $nfssweight (get_all_nfss_weights()) {
        next unless @{$from_nfss->{weight}{$nfssweight}};
        my $weight = $from_nfss->{weight}{$nfssweight}[0];
        $weight = "" if $weight eq 'regular';

        NFSSWIDTH:
        for my $nfsswidth (get_all_nfss_widths()) {
            my $nfssseries = ($nfssweight . $nfsswidth) || 'm';

            next unless @{$from_nfss->{width}{$nfsswidth}};
            my $width = $from_nfss->{width}{$nfsswidth}[0];
            $width = "" if $width eq 'regular';
            my $series = ($weight . $width) || 'regular';
            $to_nfss{$series} = $nfssseries;
        }
    }

    return [ $from_nfss, \%to_nfss ];
}


############################################################################


package Font;

# --------------------------------------------------------------------------
#   Constructor: returns a new Font object.
# --------------------------------------------------------------------------
sub _new {
    my ($class, $filename) = @_;

    my $self = {
        filename     => $filename,
        width        => 'regular',
        weight       => 'regular',
        shape        => 'roman',
        minsize      => 0,
        maxsize      => 0,
        is_smallcaps => 0,
        weight_class => 0,
        width_class  => 0,
        nfss         => 'rm',
    };

    return bless $self, $class;
}


# --------------------------------------------------------------------------
#   Factory function: parses a font's metadata and creates a Font object.
# --------------------------------------------------------------------------
sub parse {
    my $filename = shift;

    my $self = __PACKAGE__->_new($filename);

    my $metadata = _get_metadata($filename);

    $self->_parse_metadata($metadata)
         ->_parse_os2data()
         ->_parse_featuredata()
         ->_parse_sizedata()
         ->_parse_nfss_classification()
         ->_parse_fonttype()
         ;

    return $self;
}


# --------------------------------------------------------------------------
#   Returns the output of otfinfo -i as a list of key-value pairs.
# --------------------------------------------------------------------------
sub _get_metadata {
    my $filename = shift;

    my $cmd = qq(otfinfo --info "$filename");
    open my $otfinfo, '-|', $cmd
        or die "[ERROR]     Could not fork(): $!";
    my %data = map { my ($k,$v) = m/\A\s* ([^:]+?) \s*:\s* ([^\r\n]+)/xms;
                     $k =~ s/\s+//xmsg;
                     (lc $k => $v);
                   }
                   grep { m/\A\s* [^:]+? \s*:\s* [^\r\n]+/xms } <$otfinfo>;
    close $otfinfo
        or die "[ERROR]     '$cmd' failed.";

    return \%data;
}


# --------------------------------------------------------------------------
#   Processes the basic metadata for this font.
# --------------------------------------------------------------------------
sub _parse_metadata {
    my ($self, $data) = @_;

    $self->{originalfamily} = $data->{family};

    for my $key (keys %{$data}) {
        $data->{$key} =~ s/\s+//xmsg;
    }

    $data->{family}    =  $data->{preferredfamily} || $data->{family};
    $data->{subfamily} =  $data->{preferredsubfamily} || $data->{subfamily};
    $data->{fullname}  =~ s/\A$data->{family}//xms;
    $data->{fullname}  =  lc $data->{fullname};

    # clean up family name (it's used in LaTeX command names)
    my @DIGITS = qw(Zero One Two Three Four Five Six Seven Eight Nine);
    $data->{family}    =~ s/(?: LT | MT)(?: Std | Pro )\z//xms;
    $data->{family}    =~ s/(\d)/$DIGITS[$1]/xmsge;
    $data->{family}    =~ s/[^A-Za-z]+//xmsg;

    if ($data->{family} =~ s/\A DTL//xms) {
        $data->{subfamily} =~ s/\A (?: ST | T | SD | D)//xms;
    }

    # remove Adobe's SmallText size, to avoid mistaking it for Text weight
    for my $fieldname (qw(family subfamily fullname)) {
        $data->{$fieldname} =~ s/(?: SmallText | SmText )\z//xmsi;
    }

    # Sometimes the relevant info is in Fullname, sometimes in Subfamily;
    # so we need to test against both
    my $fullinfo = lc "$data->{subfamily} | $data->{fullname}";

    # We need to be careful when parsing the font info; in particular
    # we must parse strings like 'UltraCondensed' as 'Regular' weight
    # and 'UltraCondensed' width, not as 'Ultra' weight and 'Condensed' width.
    # The following rules should prevent accidents:
    # 1.  Search for matching widths before matching weights
    #     (as none of the widths is a proper substring of some weight)
    # 2.  Remove any recognised search string from the 'fullinfo'
    # 3.  Test the weights 'medium' and 'regular' *last*, since these strings
    #     may also occur in Subfamily without indicating the weight;
    #     so we only take them to mean weight if we find no other hit.
    my @widths = Attr::get_all_widths();
    for my $width (@widths) {
        if ($fullinfo =~ m/$width/xms) {
            $self->{width} = $width;
            my $widths = join '|', @widths;
            $fullinfo =~ s/$widths//gxmsi;
            last;
        }
    }
    my @weights = Attr::get_all_weights();
    for my $weight (@weights) {
        if ($fullinfo =~ m/$weight/xms) {
            $self->{weight} = $weight;
            my $weights = join '|', @weights;
            $fullinfo =~ s/$weights//gxmsi;
            last;
        }
    }
    my @shapes = Attr::get_all_shapes();
    for my $shape (@shapes) {
        if ($fullinfo =~ m/$shape/xms) {
            $self->{shape} = $shape;
            my $shapes = join '|', @shapes;
            $fullinfo =~ s/$shapes//gxmsi;
            last;
        }
    }

    # In many font families, each font is in a subfamily of its own;
    # so we remove width, weight and shape from the 'subfamily' value.
    $data->{subfamily} =~ s/$self->{width}//xmsi;
    $data->{subfamily} =~ s/$self->{weight}//xmsi;
    $data->{subfamily} =~ s/$self->{shape}//xmsi;

    $self->{name}      = $data->{postscriptname};
    $self->{family}    = $data->{family};
    $self->{subfamily} = $data->{subfamily};

    # Take care to unabbreviate weight and width; CondensedUltra fonts
    # might end up as 'ultracondensed' instead of 'ultrablackcondensed'!
    $self->{width}  = Attr::unabbreviate($self->{width});
    $self->{weight} = Attr::unabbreviate($self->{weight});
    $self->{shape}  = Attr::unabbreviate($self->{shape});

    # Some font families put small caps into separate families;
    # we merge these into the 'main' family.
    # We have to test both 'family', 'subfamily' and 'name' for hints
    # that this is a small caps font, as some fonts (e.g., Dolly)
    # only mention this in their name.
    my $shapes = join '|', Util::sort_desc_length(qw(smallcaps sc smcp caps));
    if ($self->{family} =~ m/(.+?) (?: $shapes) \z/xmsi) {
        $self->{family}       = $1;
        $self->{is_smallcaps} = 1;
    }
    if ($self->{subfamily} =~ m/(.+?) (?: $shapes) \z/xmsi) {
        $self->{subfamily}    = $1;
        $self->{is_smallcaps} = 1;
    }
    if ($self->{name} =~ m/\A DTL/xms && $self->{subfamily} =~ s/Caps//xms) {
        $self->{is_smallcaps} = 1;
    }
    if ($self->{name} =~ m/(.+?) (?: $shapes) \z/xmsi) {
        $self->{is_smallcaps} = 1;
    }
    # Some font families put italic shapes into separate families;
    # we merge these into the 'main' family.
    $shapes = join '|', Util::sort_desc_length(qw(it italic));
    if ($self->{family} =~ m/(.+?) ($shapes) \z/xmsi
            and ($self->{shape} eq 'regular'
                    or $self->{shape} eq Attr::unabbreviate(lc($2)))) {
        $self->{family} = $1;
        $self->{shape}  = Attr::unabbreviate(lc($2));
    }

    # Some font families put different widths into separate families;
    # we merge these into the 'main' font family.
    my $widths = join '|', Attr::get_all_widths();
    if ($self->{family} =~ m/(.+?) ($widths) \z/xmsi
            and ($self->{width} eq 'regular'
                    or $self->{width} eq Attr::unabbreviate(lc($2)))) {
        $self->{family} = $1;
        $self->{width}  = Attr::unabbreviate(lc($2));
    }

    # Some font families put unusual weights into separate families;
    # we merge these into the 'main' font family. But we have to be
    # careful with the word 'Text': this might be part of the family name
    # (i.e., Libre Caslon Text) and should not be mistaken for a weight.
    my $weights = join '|', Attr::get_all_weights();
    if ($self->{family} =~ m/text \z/xmsi) {
        $weights =~ s/[|]? text//xms;
    }
    if ($self->{family} =~ m/(.+?) ($weights) \z/xmsi
            and ($self->{weight} eq 'regular'
                    or $self->{weight} eq Attr::unabbreviate(lc($2)))) {
        $self->{family} = $1;
        $self->{weight} = Attr::unabbreviate(lc($2));
    }

    $self->{basicshape} = Attr::to_nfss($self->{shape});

    # We define 'series' as 'weight + width'. This matches NFSS,
    # but contradicts how most fonts are named (which is 'width + weight').
    $self->{series}
        = ($self->{width}  eq 'regular') ? $self->{weight}
        : ($self->{weight} eq 'regular') ? $self->{width}
        :                                  $self->{weight} . $self->{width}
        ;

    return $self;
}


# --------------------------------------------------------------------------
#   Parses usWeightClass and usWidthClass from the OS/2 table.
# --------------------------------------------------------------------------
sub _parse_os2data {
    my $self = shift;

    my $os2_table;
    eval {
        my $cmd = qq(otfinfo --dump-table "OS/2" "$self->{filename}");
        open my $otfinfo, '-|:raw', $cmd
            or die "could not fork(): $!";
        $os2_table = do { local $/; <$otfinfo> };
        close $otfinfo
            or die "'$cmd' failed";
    } or warn "[WARNING]   $@";

    my ($weight_class, $width_class) = unpack '@4n @6n', $os2_table;

    $self->{weight_class} = $weight_class;
    $self->{width_class}  = $width_class;

    return $self;
}


# --------------------------------------------------------------------------
#   Returns a list of features that this font supports.
#   We include 'kern' in this list even if there is only a 'kern' table
#   (but no feature), since otftotfm can also use the (legacy) table.
# --------------------------------------------------------------------------
sub _parse_featuredata {
    my $self = shift;

    my $cmd = qq(otfinfo --features "$self->{filename}");
    open my $otfinfo, '-|', $cmd
        or die "[ERROR]     Could not fork(): $!";
    my @data = map { substr $_, 0, 4 } <$otfinfo>;
    close $otfinfo
        or die "[ERROR]     '$cmd' failed.";

    $cmd = qq(otfinfo --tables "$self->{filename}");
    open $otfinfo, '-|', $cmd
        or die "[ERROR]     Could not fork(): $!";
    my $data = do { local $/; <$otfinfo> };
    close $otfinfo
        or die "[ERROR]     '$cmd' failed.";

    if ($data =~ m/\d+ \s+ kern/xms) {
        push @data, 'kern';
    }

    %{$self->{feature}} = map { $_ => 1 } @data;

    return $self;
}


# --------------------------------------------------------------------------
#   Extracts 'minsize' and 'maxsize' from the optical design size info.
# --------------------------------------------------------------------------
sub _parse_sizedata {
    my $self = shift;

    my $cmd = qq(otfinfo --optical-size "$self->{filename}");
    open my $otfinfo, '-|', $cmd
        or die "[ERROR]     Could not fork(): $!";
    my $data = do { local $/; <$otfinfo> };
    close $otfinfo
        or die "[ERROR]     '$cmd' failed.";

    my ($minsize, $maxsize)
        = $data =~ m/[(] ([\d.]+) \s* pt, \s*
                         ([\d.]+) \s* pt  \s* [])]/xms;

    $minsize //= 0;
    $maxsize //= 0;

    # fix some known bugs
    if ($self->{name} eq 'GaramondPremrPro-It'
        && $minsize == 6 && $maxsize == 8.9) {
        ($minsize, $maxsize) = (8.9, 14.9);
    }
    elsif ($self->{family} eq 'KeplerStd'
        && $self->{subfamily} =~ m/Caption/xms
        && $minsize == 8.9 && $maxsize == 13.9) {
        ($minsize, $maxsize) = (6, 8.9);
    }
    elsif ($self->{family} eq 'KeplerStd'
        && $self->{subfamily} =~ m/Subhead/xms
        && $minsize == 8.9 && $maxsize == 13.9) {
        ($minsize, $maxsize) = (13.9, 23);
    }
    elsif ($self->{family} eq 'KeplerStd'
        && $self->{subfamily} =~ m/Display/xms
        && $minsize == 8.9 && $maxsize == 13.9) {
        ($minsize, $maxsize) = (23, 72);
    }

    @{$self}{qw(minsize maxsize)} = ($minsize, $maxsize);

    return $self;
}


# --------------------------------------------------------------------------
#   Adds the NFSS classification (rm, sf, tt) to self.
# --------------------------------------------------------------------------
sub _parse_nfss_classification {
    my $self = shift;

    my $classification;
    eval {
        my $cmd = qq(otfinfo --dump-table "post" "$self->{filename}");
        open my $otfinfo, '-|:raw', $cmd
            or die "could not fork(): $!";
        my $post_table = do { local $/; <$otfinfo> };
        close $otfinfo
            or die "'$cmd' failed";

        my $is_fixed_pitch = unpack '@12N', $post_table;

        $self->{nfss} = $is_fixed_pitch                          ? 'tt'
                      : $self->{filename} =~ m/mono(?!type)/xmsi ? 'tt'
                      : $self->{filename} =~ m/sans/xmsi         ? 'sf'
                      :                                            'rm'
                      ;
    } or warn "[WARNING]   $@";

    return $self;
}


# --------------------------------------------------------------------------
#   Determines the OpenType flavor of this font.
# --------------------------------------------------------------------------
sub _parse_fonttype() {
    my $self = shift;

    my ($ext) = $self->{filename} =~ m/[.] ([^.]+) \z/xmsi;
    $ext = lc $ext;

    $self->{fonttype}
        = $ext eq 'otf' ? 'opentype'
        : $ext eq 'ttf' ? 'truetype'
        :                 ''
        ;

    if (!$self->{fonttype}) {
        open my $fontfile, '<:raw', $self->{filename}
            or die "[ERROR]     Could not open '$self->{filename}': $!";
        my $fontsignature;
        read $fontfile, $fontsignature, 4;
        $self->{fonttype}
            = $fontsignature eq 'OTTO'             ? 'opentype'
            : $fontsignature eq "\x00\x01\x00\x00" ? 'truetype'
            :                                        ''
            ;
        close $fontfile;
    }

    if (!$self->{fonttype}) {
        die "[ERROR]     Unknown font type ($self->{filename})"
    }

    return $self;
}


# Error messages, used in assert_unique().
my $ERR_DETAIL =<<'END_ERR_DETAIL';
[ERROR]     I've parsed both %s
                         and %s as

            Family:     %s
            Weight:     %s
            Width:      %s
            Shape:      %s
            Size:       %s-%s
            Smallcaps:  %s

END_ERR_DETAIL

my $ERR_PARSE =<<'END_ERR_PARSE';
[ERROR]     I failed to parse all fonts in a unique way;
            presumably some fonts have unusual widths, weights or shapes.

            Try one of the following:
            -   Run 'autoinst' on a smaller set of fonts,
                omitting the ones that weren't parsed correctly;
            -   Add the missing widths, weights or shapes to the tables
                'WIDTH', 'WEIGHT' or 'SHAPE' in the source code;

            Please also send a bug report to the author.
END_ERR_PARSE

# --------------------------------------------------------------------------
#   Asserts all parsed fonts are unique.
# --------------------------------------------------------------------------
sub assert_unique {
    my ($log, $fontlist) = @_;

    # These attributes should uniquely identify each font.
    my @attributes
        = qw(family weight width shape minsize maxsize is_smallcaps);

    my (%seen, $err_details);
    for my $font (@{$fontlist}) {
        my $key = join "\x00", @{$font}{@attributes};

        if ($seen{$key}) {
            $err_details .= sprintf $ERR_DETAIL,
                                    $seen{$key}{filename},
                                    $font->{filename},
                                    @{$font}{@attributes};
        }
        else {
             $seen{$key} = $font;
        }
    }

    # Die with detailed error message if the font infos aren't unique.
    if ($err_details) {
        $log->log($err_details, $ERR_PARSE);
        die $err_details, $ERR_PARSE;
    }

    return 1;
}


############################################################################


package LaTeX;

# --------------------------------------------------------------------------
#   Creates .sty and .fd files for LaTeX.
# --------------------------------------------------------------------------
sub create_support_files {
    my ($worklist, $family, $nfss_mapping) = @_;

    # Organize the worklist by family, encoding, style, series and shape.
    my %fddata;
    for my $workitem (@{$worklist}) {
        my $encoding    = $workitem->{encoding};
        my $figurestyle = $workitem->{figurestyle};
        my $series      = $workitem->{font}{series};
        my $shape       = $workitem->{fdshape};
        my $minsize     = $workitem->{font}{minsize};
        my $maxsize     = $workitem->{font}{maxsize};

        push @{$fddata{$encoding}{$figurestyle}{$series}{$shape}},
             [ $minsize, $maxsize, $workitem->{fontname} ];
    }

    create_stylefile($nfss_mapping, $family, \%fddata);
    while (my ($enc, $encdata) = each %fddata) {
        while (my ($sty, $stydata) = each %$encdata) {
            create_fdfile($nfss_mapping, $family, $enc, $sty, $stydata);
        }
    }

    return;
}


# This table is used to generate extra ssub rules in .fd files
# to map missing Slanted shapes to Italic and vice versa.
my %SSUB_SHAPE = (
    sl      =>  'it',
    scsl    =>  'scit',
    it      =>  'sl',
    scit    =>  'scsl',
);

# --------------------------------------------------------------------------
#   Creates a LaTeX style file.
# --------------------------------------------------------------------------
sub create_stylefile {
    my ($nfss_mapping, $fam, $data) = @_;

    my %seen = %{Util::get_keys($data)};

    my $fn = sprintf "%s.sty", $fam;
    my $dir = File::Spec->catdir(
        $ARGV{target}, 'tex', 'latex', $ARGV{typeface} || $fam);
    File::Path::make_path($dir);
    $fn = File::Spec->catfile($dir, $fn);
    open my $STY, '>', $fn or die "[ERROR]     Can't create '$fn': $!";
    # We use binmode since TeX expects these files to have
    # Unix-style line ends even on Windows.
    binmode $STY;

    print {$STY} <<"END_STY_HEADER";
\\NeedsTeXFormat{LaTeX2e}
\\ProvidesPackage{$fam}
    [$TODAY (autoinst)  Style file for $fam fonts.]

END_STY_HEADER

    print {$STY} <<"END_STY_XKEYVAL";
\\RequirePackage{xkeyval}
\\newcommand*{\\$fam\@scale}{1}
\\DeclareOptionX{scale}{\\renewcommand*{\\$fam\@scale}{#1}}
\\DeclareOptionX{scaled}{\\renewcommand*{\\$fam\@scale}{#1}}

END_STY_XKEYVAL

    if ($seen{LF} or $seen{TLF}) {
        print {$STY}
            "\\DeclareOptionX{lining}{\\edef\\$fam\@figurestyle{LF}}\n";
    }
    if ($seen{OsF} or $seen{TOsF}) {
        print {$STY}
            "\\DeclareOptionX{oldstyle}{\\edef\\$fam\@figurestyle{OsF}}\n";
    }
    if ($seen{TLF} or $seen{TOsF}) {
        print {$STY}
            "\\DeclareOptionX{tabular}{\\edef\\$fam\@figurealign{T}}\n";
    }
    if ($seen{LF} or $seen{OsF}) {
        print {$STY}
            "\\DeclareOptionX{proportional}{\\edef\\$fam\@figurealign{}}\n";
    }

    print {$STY} <<"END_STY_MAINFONT";
\\DeclareOptionX{mainfont}{
    \\renewcommand{\\familydefault}{\\$ARGV{nfss}default}
}
END_STY_MAINFONT

    my $defaults
        = $seen{OsF}  ? 'oldstyle,proportional'
        : $seen{TOsF} ? 'oldstyle,tabular'
        : $seen{LF}   ? 'lining,proportional'
        : $seen{TLF}  ? 'lining,tabular'
        :               die "[ERROR]     Internal bug, please report!"
        ;

    for my $series (qw(heavy black extrabold demibold semibold bold)) {
        if ( $seen{$series} ) {
            print {$STY}
                "\\DeclareOptionX{$series}{\\edef\\bfseries\@$ARGV{nfss}",
                "{$series}}\n";
        }
    }

    for my $series (qw(medium book text normal regular)) {
        if ( $seen{$series} ) {
            print {$STY}
                "\\DeclareOptionX{$series}{\\edef\\mdseries\@$ARGV{nfss}",
                "{$series}}\n";
        }
    }

    if ($ARGV{math}) {
        print {$STY} <<"END_STY_MATHOPTION";
\\newif\\if$fam\@math\\$fam\@mathfalse
\\DeclareOptionX{math}{\\$fam\@mathtrue}
\\DeclareOptionX{nomath}{\\$fam\@mathfalse}

\\newif\\if$fam\@mathgreek\\$fam\@mathgreektrue
\\DeclareOptionX{mathgreek}{\\$fam\@mathgreektrue}
\\DeclareOptionX{nomathgreek}{\\$fam\@mathgreekfalse}

\\newcommand*{\\$fam\@mathstyle}{TeX}
\\DeclareOptionX{math-style}{\\renewcommand*{\\$fam\@mathstyle}{#1}}

END_STY_MATHOPTION

        if ($seen{LF} or $seen{TLF}) {
            print {$STY} "\\newcommand*{\\$fam\@mathfigurestyle}{LF}\n";
        }
        elsif ($seen{OsF} or $seen{TOsF}) {
            print {$STY} "\\newcommand*{\\$fam\@mathfigurestyle}{OsF}\n";
        }

        if ($seen{OsF} or $seen{TOsF}) {
            print {$STY}
                "\\DeclareOptionX{matholdstyle}\n",
                "    {\\renewcommand*{\\$fam\@mathfigurestyle}{OsF}}\n";
        }
        if ($seen{LF} or $seen{TLF}) {
            print {$STY}
                "\\DeclareOptionX{mathlining}\n",
                "    {\\renewcommand{\\$fam\@mathfigurestyle}{LF}}\n";
        }
        print {$STY} "\n";

        if ($seen{sw}) {
            print {$STY} <<"END_STY_MATHCALOPTION";
\\newif\\if$fam\@mathcal\\$fam\@mathcalfalse
\\DeclareOptionX{mathcal}{\\$fam\@mathcaltrue}

END_STY_MATHCALOPTION
        }
    }

    print {$STY} <<"END_STY_PROCESSOPTIONS";
\\ExecuteOptionsX{$defaults}
\\ProcessOptionsX\\relax

END_STY_PROCESSOPTIONS

    print {$STY} <<"END_STY_PACKAGES";
\\RequirePackage{@{[ $seen{TS1} ? "fontenc,textcomp" : "fontenc" ]}}
\\RequirePackage{ifthen}
\\RequirePackage{mweights}

END_STY_PACKAGES

    print {$STY} <<'END_STY_FONTAXES_START';
\IfFileExists{fontaxes.sty}{
    \RequirePackage{fontaxes}
END_STY_FONTAXES_START

    if ($seen{nw} or $seen{sw}) {
        print {$STY} <<'END_STY_FONTAXES_SW';
    \DeclareRobustCommand\swshape{\not@math@alphabet\swshape\relax
        \fontprimaryshape\itdefault\fontsecondaryshape\swdefault\selectfont}
    \fa@naming@exception{shape}{{n}{sw}}{nw}
    \fa@naming@exception{shape}{{it}{sw}}{sw}

END_STY_FONTAXES_SW
    }

    if ($seen{Sup}) {
        print {$STY} <<'END_STY_FONTAXES_SUP';
    \fa@naming@exception{figures}{{superior}{proportional}}{Sup}
    \fa@naming@exception{figures}{{superior}{tabular}}{Sup}
    \def\supfigures{\@nomath\supfigures
        \fontfigurestyle{superior}\selectfont}
    \let\sufigures\supfigures
    \DeclareTextFontCommand{\textsup}{\supfigures}
    \let\textsu\textsup
    \let\textsuperior\textsup

END_STY_FONTAXES_SUP
    }

    if ($seen{Inf}) {
        print {$STY} <<'END_STY_FONTAXES_INF';
    \fa@naming@exception{figures}{{inferior}{proportional}}{Inf}
    \fa@naming@exception{figures}{{inferior}{tabular}}{Inf}
    \def\inffigures{\@nomath\inffigures
        \fontfigurestyle{inferior}\selectfont}
    \let\infigures\inffigures
    \DeclareTextFontCommand{\textinf}{\inffigures}
    \let\textin\textinf
    \let\textinferior\textinf

END_STY_FONTAXES_INF
    }

    if ($seen{Titl}) {
        print {$STY} <<'END_STY_FONTAXES_TITL';
    \fa@naming@exception{figures}{{titlingshape}{proportional}}{Titl}
    \fa@naming@exception{figures}{{titlingshape}{tabular}}{Titl}
    \def\tlshape{\@nomath\tlshape
        \fontfigurestyle{titlingshape}\selectfont}
    \DeclareTextFontCommand{\texttl}{\tlshape}
    \let\texttitling\texttl

END_STY_FONTAXES_TITL
    }

    if ($seen{Orn}) {
        print {$STY} <<'END_STY_FONTAXES_ORN';
    \fa@naming@exception{figures}{{ornament}{proportional}}{Orn}
    \fa@naming@exception{figures}{{ornament}{tabular}}{Orn}
    \def\ornaments{\@nomath\ornaments
        \fontencoding{U}\fontfigurestyle{ornament}\selectfont}
    \DeclareTextFontCommand{\textornaments}{\ornaments}

END_STY_FONTAXES_ORN
    }

    if ($seen{Numr}) {
        print {$STY} <<'END_STY_FONTAXES_NUMR';
    \fa@naming@exception{figures}{{numerators}{proportional}}{Numr}
    \fa@naming@exception{figures}{{numerators}{tabular}}{Numr}

END_STY_FONTAXES_NUMR
    }

    if ($seen{Dnom}) {
        print {$STY} <<'END_STY_FONTAXES_DNOM';
    \fa@naming@exception{figures}{{denominators}{proportional}}{Dnom}
    \fa@naming@exception{figures}{{denominators}{tabular}}{Dnom}

END_STY_FONTAXES_DNOM
    }

    print {$STY} "}{}\n\n";

    #   For the scale=MatchLowercase option, we need the name for
    #   one of the fonts from the family, to pass to plain TeX's
    #   \font macro (as explained below, we cannot use NFSS's
    #   font loading mechanism before we have calculated the correct
    #   scaling parameter).
    my $testfont = eval {
        my $testenc = $ARGV{encoding}[0];
        my $testfig = ( grep { exists $data->{$testenc}{$_} }
                             qw(OsF LF TOsF TLF) )[0] or die;
        my $testweight = ( grep { $nfss_mapping->{$_} eq "m" }
                                keys %{$nfss_mapping} )[0] or die;
        my $testshape
            = ( grep { exists $data->{$testenc}{$testfig}{$testweight}{$_} }
                     qw(n sc it sl)
              )[0] or die;
        return $data->{$testenc}{$testfig}{$testweight}{$testshape}[0][2]
            || die;
    };

    if (defined $testfont) {
        print {$STY} <<"END_STY_MATCHLOWERCASE";
%   Here we implement the scale=MatchLowercase option.
%   If this is given, we must compute the correct value of
%   the "\\$fam\@scale" parameter before loading the .fd files;
%   but to determine that value we of course need the font's x-height.
%   To avoid triggering the loading of .fd files,
%   we use plain TeX's \\font primitive to load the testfont.
%   We then compute the ratio of the current x-height to our font's x-height;
%   this is the "\\$fam\@scale" we will pass to the .fd files.
\\ifthenelse{\\equal{\\$fam\@scale}{MatchLowercase}}
    {   \\newlength{\\$fam\@currentx}
        \\settoheight{\\$fam\@currentx}{x}
        \\newlength{\\$fam\@xheight}
        \\settoheight{\\$fam\@xheight}
            {{\\font\\testfont=$testfont at \\f\@size pt\\testfont x}}
        \\renewcommand*{\\$fam\@scale}
            {\\strip\@pt\\dimexpr\\number\\numexpr\\number\\dimexpr\\$fam\@currentx\\relax*65536/\\number\\dimexpr\\$fam\@xheight\\relax\\relax sp\\relax}}
    {}

END_STY_MATCHLOWERCASE
    }

    print {$STY} <<"END_STYLE_REST";
\\renewcommand*
    {\\$ARGV{nfss}default}
    {$fam-\\$fam\@figurealign\\$fam\@figurestyle}

END_STYLE_REST

    if ($ARGV{math}) {
        print {$STY} <<"END_STY_MATH";
\\newif\\if$fam\@mathLATINup\\$fam\@mathLATINupfalse
\\newif\\if$fam\@mathlatinup\\$fam\@mathlatinupfalse
\\newif\\if$fam\@mathGREEKup\\$fam\@mathGREEKupfalse
\\newif\\if$fam\@mathgreekup\\$fam\@mathgreekupfalse

\\if$fam\@math
    \\DeclareSymbolFont{newoperators}  {OT1}{$fam-\\$fam\@figurealign\\$fam\@mathfigurestyle}{\\mdseries\@$ARGV{nfss}}{n}
    \\SetSymbolFont{newoperators}{bold}{OT1}{$fam-\\$fam\@figurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{n}

    \\DeclareSymbolFont{newletters}  {OML}{$fam-\\$fam\@figurealign\\$fam\@mathfigurestyle}{\\mdseries\@$ARGV{nfss}}{it}
    \\SetSymbolFont{newletters}{bold}{OML}{$fam-\\$fam\@figurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{it}

    \\DeclareSymbolFontAlphabet{\\mathrm}{newoperators}
    \\DeclareSymbolFontAlphabet{\\mathnormal}{newletters}

    \\def\\operator\@font{\\mathgroup\\symnewoperators}
    \\SetMathAlphabet{\\mathit}{normal}{OT1}{$fam-\\$fam\@figurealign\\$fam\@mathfigurestyle}{\\mdseries\@$ARGV{nfss}}{it}
    \\SetMathAlphabet{\\mathit}{bold}  {OT1}{$fam-\\$fam\@figurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{it}

    \\SetMathAlphabet{\\mathbf}{normal}{OT1}{$fam-\\$fam\@figurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{n}
    \\SetMathAlphabet{\\mathbf}{bold}  {OT1}{$fam-\\$fam\@figurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{n}

    \\def\\re\@DeclareMathSymbol#1#2#3#4{%
        \\if\\relax\\noexpand#1\\let#1=\\undefined\\fi
        \\DeclareMathSymbol{#1}{#2}{#3}{#4}}

    \\def\\re\@DeclareMathDelimiter#1#2#3#4#5#6{%
        \\let#1=\\undefined
        \\DeclareMathDelimiter{#1}{#2}{#3}{#4}{#5}{#6}}

    \\def\\re\@DeclareMathAccent#1#2#3#4{%
        \\let#1=\\undefined
        \\DeclareMathAccent{#1}{#2}{#3}{#4}}

    \\re\@DeclareMathSymbol{0}{\\mathalpha}{newoperators}{`0}
    \\re\@DeclareMathSymbol{1}{\\mathalpha}{newoperators}{`1}
    \\re\@DeclareMathSymbol{2}{\\mathalpha}{newoperators}{`2}
    \\re\@DeclareMathSymbol{3}{\\mathalpha}{newoperators}{`3}
    \\re\@DeclareMathSymbol{4}{\\mathalpha}{newoperators}{`4}
    \\re\@DeclareMathSymbol{5}{\\mathalpha}{newoperators}{`5}
    \\re\@DeclareMathSymbol{6}{\\mathalpha}{newoperators}{`6}
    \\re\@DeclareMathSymbol{7}{\\mathalpha}{newoperators}{`7}
    \\re\@DeclareMathSymbol{8}{\\mathalpha}{newoperators}{`8}
    \\re\@DeclareMathSymbol{9}{\\mathalpha}{newoperators}{`9}

    \\re\@DeclareMathSymbol{a}{\\mathalpha}{newletters}{`a}
    \\re\@DeclareMathSymbol{b}{\\mathalpha}{newletters}{`b}
    \\re\@DeclareMathSymbol{c}{\\mathalpha}{newletters}{`c}
    \\re\@DeclareMathSymbol{d}{\\mathalpha}{newletters}{`d}
    \\re\@DeclareMathSymbol{e}{\\mathalpha}{newletters}{`e}
    \\re\@DeclareMathSymbol{f}{\\mathalpha}{newletters}{`f}
    \\re\@DeclareMathSymbol{g}{\\mathalpha}{newletters}{`g}
    \\re\@DeclareMathSymbol{h}{\\mathalpha}{newletters}{`h}
    \\re\@DeclareMathSymbol{i}{\\mathalpha}{newletters}{`i}
    \\re\@DeclareMathSymbol{j}{\\mathalpha}{newletters}{`j}
    \\re\@DeclareMathSymbol{k}{\\mathalpha}{newletters}{`k}
    \\re\@DeclareMathSymbol{l}{\\mathalpha}{newletters}{`l}
    \\re\@DeclareMathSymbol{m}{\\mathalpha}{newletters}{`m}
    \\re\@DeclareMathSymbol{n}{\\mathalpha}{newletters}{`n}
    \\re\@DeclareMathSymbol{o}{\\mathalpha}{newletters}{`o}
    \\re\@DeclareMathSymbol{p}{\\mathalpha}{newletters}{`p}
    \\re\@DeclareMathSymbol{q}{\\mathalpha}{newletters}{`q}
    \\re\@DeclareMathSymbol{r}{\\mathalpha}{newletters}{`r}
    \\re\@DeclareMathSymbol{s}{\\mathalpha}{newletters}{`s}
    \\re\@DeclareMathSymbol{t}{\\mathalpha}{newletters}{`t}
    \\re\@DeclareMathSymbol{u}{\\mathalpha}{newletters}{`u}
    \\re\@DeclareMathSymbol{v}{\\mathalpha}{newletters}{`v}
    \\re\@DeclareMathSymbol{w}{\\mathalpha}{newletters}{`w}
    \\re\@DeclareMathSymbol{x}{\\mathalpha}{newletters}{`x}
    \\re\@DeclareMathSymbol{y}{\\mathalpha}{newletters}{`y}
    \\re\@DeclareMathSymbol{z}{\\mathalpha}{newletters}{`z}

    \\re\@DeclareMathSymbol{A}{\\mathalpha}{newletters}{`A}
    \\re\@DeclareMathSymbol{B}{\\mathalpha}{newletters}{`B}
    \\re\@DeclareMathSymbol{C}{\\mathalpha}{newletters}{`C}
    \\re\@DeclareMathSymbol{D}{\\mathalpha}{newletters}{`D}
    \\re\@DeclareMathSymbol{E}{\\mathalpha}{newletters}{`E}
    \\re\@DeclareMathSymbol{F}{\\mathalpha}{newletters}{`F}
    \\re\@DeclareMathSymbol{G}{\\mathalpha}{newletters}{`G}
    \\re\@DeclareMathSymbol{H}{\\mathalpha}{newletters}{`H}
    \\re\@DeclareMathSymbol{I}{\\mathalpha}{newletters}{`I}
    \\re\@DeclareMathSymbol{J}{\\mathalpha}{newletters}{`J}
    \\re\@DeclareMathSymbol{K}{\\mathalpha}{newletters}{`K}
    \\re\@DeclareMathSymbol{L}{\\mathalpha}{newletters}{`L}
    \\re\@DeclareMathSymbol{M}{\\mathalpha}{newletters}{`M}
    \\re\@DeclareMathSymbol{N}{\\mathalpha}{newletters}{`N}
    \\re\@DeclareMathSymbol{O}{\\mathalpha}{newletters}{`O}
    \\re\@DeclareMathSymbol{P}{\\mathalpha}{newletters}{`P}
    \\re\@DeclareMathSymbol{Q}{\\mathalpha}{newletters}{`Q}
    \\re\@DeclareMathSymbol{R}{\\mathalpha}{newletters}{`R}
    \\re\@DeclareMathSymbol{S}{\\mathalpha}{newletters}{`S}
    \\re\@DeclareMathSymbol{T}{\\mathalpha}{newletters}{`T}
    \\re\@DeclareMathSymbol{U}{\\mathalpha}{newletters}{`U}
    \\re\@DeclareMathSymbol{V}{\\mathalpha}{newletters}{`V}
    \\re\@DeclareMathSymbol{W}{\\mathalpha}{newletters}{`W}
    \\re\@DeclareMathSymbol{X}{\\mathalpha}{newletters}{`X}
    \\re\@DeclareMathSymbol{Y}{\\mathalpha}{newletters}{`Y}
    \\re\@DeclareMathSymbol{Z}{\\mathalpha}{newletters}{`Z}

    \\re\@DeclareMathSymbol{\\imath}{\\mathord}{newletters}{"7B}
    \\re\@DeclareMathSymbol{\\jmath}{\\mathord}{newletters}{"7C}

    %
    %   A number of math symbol declarations have been commented out,
    %   since these characters generally do not work very well when
    %   typesetting maths (either because of spacing issues or because
    %   they don't mix with others symbols).
    %   The commented-out declarations have been left in this style file
    %   in case the user does want to re-activate those characters.
    %

    \\re\@DeclareMathSymbol{!}{\\mathclose}{newoperators}{"21}
  % \\re\@DeclareMathSymbol{+}{\\mathbin}  {newoperators}{"2B}
  % \\re\@DeclareMathSymbol{:}{\\mathrel}  {newoperators}{"3A}
    \\re\@DeclareMathSymbol{;}{\\mathpunct}{newoperators}{"3B}
  % \\re\@DeclareMathSymbol{=}{\\mathrel}  {newoperators}{"3D}
    \\re\@DeclareMathSymbol{?}{\\mathclose}{newoperators}{"3F}

  % \\re\@DeclareMathSymbol{.}{\\mathord}  {newletters}{"3A}
    \\re\@DeclareMathSymbol{,}{\\mathpunct}{newletters}{"3B}
  % \\re\@DeclareMathSymbol{<}{\\mathrel}  {newletters}{"3C}
  % \\re\@DeclareMathSymbol{/}{\\mathord}  {newletters}{"3D}
  % \\re\@DeclareMathSymbol{>}{\\mathrel}  {newletters}{"3E}

    \\re\@DeclareMathSymbol{\\mathdollar}{\\mathord}  {newoperators}{"24}
    \\re\@DeclareMathSymbol{\\colon}     {\\mathpunct}{newoperators}{"3A}

  % \\DeclareMathDelimiter{(}{\\mathopen} {newoperators}{"28}{largesymbols}{"00}
  % \\DeclareMathDelimiter{)}{\\mathclose}{newoperators}{"29}{largesymbols}{"01}
  % \\DeclareMathDelimiter{[}{\\mathopen} {newoperators}{"5B}{largesymbols}{"02}
  % \\DeclareMathDelimiter{]}{\\mathclose}{newoperators}{"5D}{largesymbols}{"03}
  % \\DeclareMathDelimiter{/}{\\mathord}  {newoperators}{"2F}{largesymbols}{"0E}

    \\re\@DeclareMathAccent{\\grave}   {\\mathalpha}{newoperators}{"12}
    \\re\@DeclareMathAccent{\\acute}   {\\mathalpha}{newoperators}{"13}
    \\re\@DeclareMathAccent{\\check}   {\\mathalpha}{newoperators}{"14}
    \\re\@DeclareMathAccent{\\breve}   {\\mathalpha}{newoperators}{"15}
    \\re\@DeclareMathAccent{\\bar}     {\\mathalpha}{newoperators}{"16}
    \\re\@DeclareMathAccent{\\mathring}{\\mathalpha}{newoperators}{"17}
    \\re\@DeclareMathAccent{\\hat}     {\\mathalpha}{newoperators}{"5E}
    \\re\@DeclareMathAccent{\\dot}     {\\mathalpha}{newoperators}{"5F}
    \\re\@DeclareMathAccent{\\tilde}   {\\mathalpha}{newoperators}{"7E}
    \\re\@DeclareMathAccent{\\ddot}    {\\mathalpha}{newoperators}{"7F}

    \\if$fam\@mathgreek
        \\re\@DeclareMathSymbol{\\Gamma}  {\\mathalpha}{newoperators}{"00}
        \\re\@DeclareMathSymbol{\\Delta}  {\\mathalpha}{newoperators}{"01}
        \\re\@DeclareMathSymbol{\\Theta}  {\\mathalpha}{newoperators}{"02}
        \\re\@DeclareMathSymbol{\\Lambda} {\\mathalpha}{newoperators}{"03}
        \\re\@DeclareMathSymbol{\\Xi}     {\\mathalpha}{newoperators}{"04}
        \\re\@DeclareMathSymbol{\\Pi}     {\\mathalpha}{newoperators}{"05}
        \\re\@DeclareMathSymbol{\\Sigma}  {\\mathalpha}{newoperators}{"06}
        \\re\@DeclareMathSymbol{\\Upsilon}{\\mathalpha}{newoperators}{"07}
        \\re\@DeclareMathSymbol{\\Phi}    {\\mathalpha}{newoperators}{"08}
        \\re\@DeclareMathSymbol{\\Psi}    {\\mathalpha}{newoperators}{"09}
        \\re\@DeclareMathSymbol{\\Omega}  {\\mathalpha}{newoperators}{"0A}

        \\re\@DeclareMathSymbol{\\alpha}     {\\mathord}{newletters}{"0B}
        \\re\@DeclareMathSymbol{\\beta}      {\\mathord}{newletters}{"0C}
        \\re\@DeclareMathSymbol{\\gamma}     {\\mathord}{newletters}{"0D}
        \\re\@DeclareMathSymbol{\\delta}     {\\mathord}{newletters}{"0E}
        \\re\@DeclareMathSymbol{\\epsilon}   {\\mathord}{newletters}{"0F}
        \\re\@DeclareMathSymbol{\\zeta}      {\\mathord}{newletters}{"10}
        \\re\@DeclareMathSymbol{\\eta}       {\\mathord}{newletters}{"11}
        \\re\@DeclareMathSymbol{\\theta}     {\\mathord}{newletters}{"12}
        \\re\@DeclareMathSymbol{\\iota}      {\\mathord}{newletters}{"13}
        \\re\@DeclareMathSymbol{\\kappa}     {\\mathord}{newletters}{"14}
        \\re\@DeclareMathSymbol{\\lambda}    {\\mathord}{newletters}{"15}
        \\re\@DeclareMathSymbol{\\mu}        {\\mathord}{newletters}{"16}
        \\re\@DeclareMathSymbol{\\nu}        {\\mathord}{newletters}{"17}
        \\re\@DeclareMathSymbol{\\xi}        {\\mathord}{newletters}{"18}
        \\re\@DeclareMathSymbol{\\pi}        {\\mathord}{newletters}{"19}
        \\re\@DeclareMathSymbol{\\rho}       {\\mathord}{newletters}{"1A}
        \\re\@DeclareMathSymbol{\\sigma}     {\\mathord}{newletters}{"1B}
        \\re\@DeclareMathSymbol{\\tau}       {\\mathord}{newletters}{"1C}
        \\re\@DeclareMathSymbol{\\upsilon}   {\\mathord}{newletters}{"1D}
        \\re\@DeclareMathSymbol{\\phi}       {\\mathord}{newletters}{"1E}
        \\re\@DeclareMathSymbol{\\chi}       {\\mathord}{newletters}{"1F}
        \\re\@DeclareMathSymbol{\\psi}       {\\mathord}{newletters}{"20}
        \\re\@DeclareMathSymbol{\\omega}     {\\mathord}{newletters}{"21}
        \\re\@DeclareMathSymbol{\\varepsilon}{\\mathord}{newletters}{"22}
        \\re\@DeclareMathSymbol{\\vartheta}  {\\mathord}{newletters}{"23}
        \\re\@DeclareMathSymbol{\\varpi}     {\\mathord}{newletters}{"24}
        \\re\@DeclareMathSymbol{\\varrho}    {\\mathord}{newletters}{"25}
        \\re\@DeclareMathSymbol{\\varsigma}  {\\mathord}{newletters}{"26}
        \\re\@DeclareMathSymbol{\\varphi}    {\\mathord}{newletters}{"27}
    \\fi

    \\ifthenelse{\\equal{\\$fam\@mathstyle}{TeX}}
        {\\$fam\@mathGREEKuptrue}
        {}
    \\ifthenelse{\\equal{\\$fam\@mathstyle}{french}}
        {\\$fam\@mathLATINuptrue
         \\$fam\@mathGREEKuptrue
         \\$fam\@mathgreekuptrue}
        {}
    \\ifthenelse{\\equal{\\$fam\@mathstyle}{upright}}
        {\\$fam\@mathLATINuptrue
         \\$fam\@mathlatinuptrue
         \\$fam\@mathGREEKuptrue
         \\$fam\@mathgreekuptrue}
        {}

    \\if$fam\@mathLATINup
        \\re\@DeclareMathSymbol{A}{\\mathalpha}{newoperators}{`A}
        \\re\@DeclareMathSymbol{B}{\\mathalpha}{newoperators}{`B}
        \\re\@DeclareMathSymbol{C}{\\mathalpha}{newoperators}{`C}
        \\re\@DeclareMathSymbol{D}{\\mathalpha}{newoperators}{`D}
        \\re\@DeclareMathSymbol{E}{\\mathalpha}{newoperators}{`E}
        \\re\@DeclareMathSymbol{F}{\\mathalpha}{newoperators}{`F}
        \\re\@DeclareMathSymbol{G}{\\mathalpha}{newoperators}{`G}
        \\re\@DeclareMathSymbol{H}{\\mathalpha}{newoperators}{`H}
        \\re\@DeclareMathSymbol{I}{\\mathalpha}{newoperators}{`I}
        \\re\@DeclareMathSymbol{J}{\\mathalpha}{newoperators}{`J}
        \\re\@DeclareMathSymbol{K}{\\mathalpha}{newoperators}{`K}
        \\re\@DeclareMathSymbol{L}{\\mathalpha}{newoperators}{`L}
        \\re\@DeclareMathSymbol{M}{\\mathalpha}{newoperators}{`M}
        \\re\@DeclareMathSymbol{N}{\\mathalpha}{newoperators}{`N}
        \\re\@DeclareMathSymbol{O}{\\mathalpha}{newoperators}{`O}
        \\re\@DeclareMathSymbol{P}{\\mathalpha}{newoperators}{`P}
        \\re\@DeclareMathSymbol{Q}{\\mathalpha}{newoperators}{`Q}
        \\re\@DeclareMathSymbol{R}{\\mathalpha}{newoperators}{`R}
        \\re\@DeclareMathSymbol{S}{\\mathalpha}{newoperators}{`S}
        \\re\@DeclareMathSymbol{T}{\\mathalpha}{newoperators}{`T}
        \\re\@DeclareMathSymbol{U}{\\mathalpha}{newoperators}{`U}
        \\re\@DeclareMathSymbol{V}{\\mathalpha}{newoperators}{`V}
        \\re\@DeclareMathSymbol{W}{\\mathalpha}{newoperators}{`W}
        \\re\@DeclareMathSymbol{X}{\\mathalpha}{newoperators}{`X}
        \\re\@DeclareMathSymbol{Y}{\\mathalpha}{newoperators}{`Y}
        \\re\@DeclareMathSymbol{Z}{\\mathalpha}{newoperators}{`Z}
    \\fi

    \\if$fam\@mathlatinup
        \\DeclareSymbolFont{upletters}  {OML}{$fam-\\$fam\@figurealign\\$fam\@mathfigurestyle}{\\mdseries\@$ARGV{nfss}}{n}
        \\SetSymbolFont{upletters}{bold}{OML}{$fam-\\$fam\@figurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{n}

        \\re\@DeclareMathSymbol{a}{\\mathord}{upletters}{`a}
        \\re\@DeclareMathSymbol{b}{\\mathord}{upletters}{`b}
        \\re\@DeclareMathSymbol{c}{\\mathord}{upletters}{`c}
        \\re\@DeclareMathSymbol{d}{\\mathord}{upletters}{`d}
        \\re\@DeclareMathSymbol{e}{\\mathord}{upletters}{`e}
        \\re\@DeclareMathSymbol{f}{\\mathord}{upletters}{`f}
        \\re\@DeclareMathSymbol{g}{\\mathord}{upletters}{`g}
        \\re\@DeclareMathSymbol{h}{\\mathord}{upletters}{`h}
        \\re\@DeclareMathSymbol{i}{\\mathord}{upletters}{`i}
        \\re\@DeclareMathSymbol{j}{\\mathord}{upletters}{`j}
        \\re\@DeclareMathSymbol{k}{\\mathord}{upletters}{`k}
        \\re\@DeclareMathSymbol{l}{\\mathord}{upletters}{`l}
        \\re\@DeclareMathSymbol{m}{\\mathord}{upletters}{`m}
        \\re\@DeclareMathSymbol{n}{\\mathord}{upletters}{`n}
        \\re\@DeclareMathSymbol{o}{\\mathord}{upletters}{`o}
        \\re\@DeclareMathSymbol{p}{\\mathord}{upletters}{`p}
        \\re\@DeclareMathSymbol{q}{\\mathord}{upletters}{`q}
        \\re\@DeclareMathSymbol{r}{\\mathord}{upletters}{`r}
        \\re\@DeclareMathSymbol{s}{\\mathord}{upletters}{`s}
        \\re\@DeclareMathSymbol{t}{\\mathord}{upletters}{`t}
        \\re\@DeclareMathSymbol{u}{\\mathord}{upletters}{`u}
        \\re\@DeclareMathSymbol{v}{\\mathord}{upletters}{`v}
        \\re\@DeclareMathSymbol{w}{\\mathord}{upletters}{`w}
        \\re\@DeclareMathSymbol{x}{\\mathord}{upletters}{`x}
        \\re\@DeclareMathSymbol{y}{\\mathord}{upletters}{`y}
        \\re\@DeclareMathSymbol{z}{\\mathord}{upletters}{`z}

        \\re\@DeclareMathSymbol{\\imath}{\\mathord}{upletters}{"7B}
        \\re\@DeclareMathSymbol{\\jmath}{\\mathord}{upletters}{"7C}
    \\fi

    \\if$fam\@mathgreek
        \\if$fam\@mathGREEKup
        \\else
            \\re\@DeclareMathSymbol{\\Gamma}  {\\mathalpha}{newletters}{"00}
            \\re\@DeclareMathSymbol{\\Delta}  {\\mathalpha}{newletters}{"01}
            \\re\@DeclareMathSymbol{\\Theta}  {\\mathalpha}{newletters}{"02}
            \\re\@DeclareMathSymbol{\\Lambda} {\\mathalpha}{newletters}{"03}
            \\re\@DeclareMathSymbol{\\Xi}     {\\mathalpha}{newletters}{"04}
            \\re\@DeclareMathSymbol{\\Pi}     {\\mathalpha}{newletters}{"05}
            \\re\@DeclareMathSymbol{\\Sigma}  {\\mathalpha}{newletters}{"06}
            \\re\@DeclareMathSymbol{\\Upsilon}{\\mathalpha}{newletters}{"07}
            \\re\@DeclareMathSymbol{\\Phi}    {\\mathalpha}{newletters}{"08}
            \\re\@DeclareMathSymbol{\\Psi}    {\\mathalpha}{newletters}{"09}
            \\re\@DeclareMathSymbol{\\Omega}  {\\mathalpha}{newletters}{"0A}
        \\fi

        \\if$fam\@mathgreekup
            \\DeclareSymbolFont{upletters}  {OML}{$fam-\\$fam\@figurealign\\$fam\@mathfigurestyle}{\\mdseries\@$ARGV{nfss}}{n}
            \\SetSymbolFont{upletters}{bold}{OML}{$fam-\\$fam\@figurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{n}

            \\re\@DeclareMathSymbol{\\alpha}     {\\mathord}{upletters}{"0B}
            \\re\@DeclareMathSymbol{\\beta}      {\\mathord}{upletters}{"0C}
            \\re\@DeclareMathSymbol{\\gamma}     {\\mathord}{upletters}{"0D}
            \\re\@DeclareMathSymbol{\\delta}     {\\mathord}{upletters}{"0E}
            \\re\@DeclareMathSymbol{\\epsilon}   {\\mathord}{upletters}{"0F}
            \\re\@DeclareMathSymbol{\\zeta}      {\\mathord}{upletters}{"10}
            \\re\@DeclareMathSymbol{\\eta}       {\\mathord}{upletters}{"11}
            \\re\@DeclareMathSymbol{\\theta}     {\\mathord}{upletters}{"12}
            \\re\@DeclareMathSymbol{\\iota}      {\\mathord}{upletters}{"13}
            \\re\@DeclareMathSymbol{\\kappa}     {\\mathord}{upletters}{"14}
            \\re\@DeclareMathSymbol{\\lambda}    {\\mathord}{upletters}{"15}
            \\re\@DeclareMathSymbol{\\mu}        {\\mathord}{upletters}{"16}
            \\re\@DeclareMathSymbol{\\nu}        {\\mathord}{upletters}{"17}
            \\re\@DeclareMathSymbol{\\xi}        {\\mathord}{upletters}{"18}
            \\re\@DeclareMathSymbol{\\pi}        {\\mathord}{upletters}{"19}
            \\re\@DeclareMathSymbol{\\rho}       {\\mathord}{upletters}{"1A}
            \\re\@DeclareMathSymbol{\\sigma}     {\\mathord}{upletters}{"1B}
            \\re\@DeclareMathSymbol{\\tau}       {\\mathord}{upletters}{"1C}
            \\re\@DeclareMathSymbol{\\upsilon}   {\\mathord}{upletters}{"1D}
            \\re\@DeclareMathSymbol{\\phi}       {\\mathord}{upletters}{"1E}
            \\re\@DeclareMathSymbol{\\chi}       {\\mathord}{upletters}{"1F}
            \\re\@DeclareMathSymbol{\\psi}       {\\mathord}{upletters}{"20}
            \\re\@DeclareMathSymbol{\\omega}     {\\mathord}{upletters}{"21}
            \\re\@DeclareMathSymbol{\\varepsilon}{\\mathord}{upletters}{"22}
            \\re\@DeclareMathSymbol{\\vartheta}  {\\mathord}{upletters}{"23}
            \\re\@DeclareMathSymbol{\\varpi}     {\\mathord}{upletters}{"24}
            \\re\@DeclareMathSymbol{\\varrho}    {\\mathord}{upletters}{"25}
            \\re\@DeclareMathSymbol{\\varsigma}  {\\mathord}{upletters}{"26}
            \\re\@DeclareMathSymbol{\\varphi}    {\\mathord}{upletters}{"27}
        \\fi
    \\fi
\\fi

END_STY_MATH

        if ($seen{sw}) {
            print {$STY} <<"END_STY_MATHCAL";
\\if$fam\@mathcal
    \\SetMathAlphabet{\\mathcal}{normal}{OT1}{$fam-\\$fam\@figurealign\\$fam\@mathfigurestyle}{\\mdseries\@$ARGV{nfss}}{sw}
    \\SetMathAlphabet{\\mathcal}{bold}  {OT1}{$fam-\\$fam\@figurealign\\$fam\@mathfigurestyle}{\\bfseries\@$ARGV{nfss}}{sw}
\\fi

END_STY_MATHCAL
        }
    }

    print {$STY} "\\endinput\n";
    close $STY;

    return;
}


# --------------------------------------------------------------------------
#   Creates a .fd file for LaTeX.
# --------------------------------------------------------------------------
sub create_fdfile {
    my ($nfss_mapping, $fam, $enc, $sty, $data) = @_;

    my $fn = sprintf "%s%s-%s.fd", $enc, $fam, $sty;
    my $dir = File::Spec->catdir(
        $ARGV{target}, 'tex', 'latex', $ARGV{typeface} || $fam);
    File::Path::make_path($dir);
    $fn = File::Spec->catfile($dir, $fn);
    open my $FD, '>', $fn
        or die "[ERROR]     Can't create '$fn': $!";
    binmode $FD;

    print {$FD} <<"END_FD_HEADER";
%% Generated by autoinst on $TODAY
%%
\\ProvidesFile{$enc$fam-$sty.fd}
    [$TODAY (autoinst)  Font definitions for $enc/$fam-$sty.]

\\ifcsname s\@fct\@alias\\endcsname\\else
\\gdef\\s\@fct\@alias{\\sub\@sfcnt\\\@font\@aliasinfo}
\\gdef\\\@font\@aliasinfo#1{%
    \\\@font\@info{Font\\space shape\\space `\\curr\@fontshape'\\space will
        \\space be\\space aliased\\MessageBreak to\\space `\\mandatory\@arg'}%
}
\\fi

\\expandafter\\ifx\\csname $fam\@scale\\endcsname\\relax
    \\let\\$fam\@\@scale\\\@empty
\\else
    \\edef\\$fam\@\@scale{s*[\\csname $fam\@scale\\endcsname]}%
\\fi

\\DeclareFontFamily{$enc}{$fam-$sty}{@{[
    $ARGV{nfss} eq 'tt' ? '\hyphenchar\font=-1'
    : $enc eq 'OML'     ? '\skewchar\font=127'
    :                     q{}
]}}

END_FD_HEADER

    while (my ($series, $fdseries) = each %$data) {
        my $nfssseries = $nfss_mapping->{$series};

        my $alias = $series;
        if (defined $nfssseries) {
            print {$FD} "\n%   ----  $nfssseries = $series  ----\n\n";
            $series = $nfssseries;
        }
        else {
            print {$FD} "\n%   ----  $series  ----\n\n";
        }
        while (my ($shape, $fdshape) = each %$fdseries) {
            print {$FD}
                "\\DeclareFontShape{$enc}{$fam-$sty}{$series}{$shape}{\n";
            my @sizes = sort { $a->[0] <=> $b->[0] }
                                @{$fdshape};
            $sizes[0][0] = $sizes[-1][1] = '';
            $sizes[$_][0] = $sizes[$_ - 1][1] for (1 .. $#sizes);
            for my $size (@sizes) {
                print {$FD} "      <$size->[0]-$size->[1]> ",
                            "\\$fam\@\@scale $size->[2]\n";
            }
            print {$FD} "}{}\n\n";

            if (defined $nfssseries) {
                print {$FD} <<"END_ALIAS_SERIES";
\\DeclareFontShape{$enc}{$fam-$sty}{$alias}{$shape}{
      <-> alias * $fam-$sty/$nfssseries/$shape
}{}

END_ALIAS_SERIES
            }
        }

        # ssub italic for missing slanted, or vice versa
        while (my ($shape, $replace) = each %SSUB_SHAPE) {
            if (!exists $fdseries->{$shape} && exists $fdseries->{$replace}) {
                print {$FD} <<"END_SSUB_SHAPE";
\\DeclareFontShape{$enc}{$fam-$sty}{$series}{$shape}{
    <-> ssub * $fam-$sty/$series/$replace
}{}

END_SSUB_SHAPE
                if (defined $nfssseries) {
                    print {$FD} <<"END_SSUB_ALIAS";
\\DeclareFontShape{$enc}{$fam-$sty}{$alias}{$shape}{
    <-> ssub * $fam-$sty/$alias/$replace
}{}

END_SSUB_ALIAS
                }
                $fdseries->{$shape} = 1;
            }
        }
    }

    my %seen;
    while (my ($series, $nfssseries) = each %{$nfss_mapping}) {
        if (exists $data->{$series}) {
            for my $shape (keys %{$data->{$series}}) {
                $seen{$nfssseries}{$shape} = 1;
            }
        }
    }

    print {$FD} "\n%   ----  Extra 'ssub' rules to map 'bx' to 'b'  ----\n\n";
    for my $shape (keys %{$seen{b}}) {
        if (!exists $seen{bx}{$shape}) {
            print {$FD} <<"END_SSUB_BX";
\\DeclareFontShape{$enc}{$fam-$sty}{bx}{$shape}{
      <-> ssub * $fam-$sty/b/$shape
}{}

END_SSUB_BX
        }
    }

    print {$FD} "\\endinput\n";
    close $FD;

    return;
}


############################################################################


package Log;

# --------------------------------------------------------------------------
#   Constructor: creates new Log object, writing to $logfile.
# --------------------------------------------------------------------------
sub new {
    my ($class, $filename) = @_;

    if (-e $filename) {
        print "[WARNING]   File '$filename' already exists;\n" .
        "            appending new log data to end.\n";
    }
    open my $log, '>>', $filename
        or die "$0: cannot create '$filename': $!";

    return bless $log, $class;
}


# --------------------------------------------------------------------------
#   Writes a message to the log file.
# --------------------------------------------------------------------------
sub log {
    my ($self, $msg) = @_;

    print {$self} $msg;

    return;
}


# --------------------------------------------------------------------------
#   Closes the logfile associated with this Log object.
# --------------------------------------------------------------------------
sub close {
    my $self = shift;

    close $self;

    return;
}


# --------------------------------------------------------------------------
#   Logs the command line options.
# --------------------------------------------------------------------------
sub log_options {
    my $self = shift;

    print {$self} <<"END_ARGUMENTS";


############################################################################


@{[ POSIX::strftime("[%F %T]", localtime time) ]}  $0, version $VERSION

Command was:

    "$ARGV{cmdline}"

----------------------------------------------------------------------------

I'm using the following options:

    encoding(s):        @{[ join ', ', @{$ARGV{encoding}} ]}
    NFSS:               $ARGV{nfss} @{[ $ARGV{nfss} eq 'rm' ? '(serif)'
                                      : $ARGV{nfss} eq 'sf' ? '(sanserif)'
                                      : $ARGV{nfss} eq 'tt' ? '(typewriter)'
                                      :                       '(unknown)'
                                    ]}

    lining:             @{[ $ARGV{lining}       ? 'yes'     : 'no'     ]}
    oldstyle:           @{[ $ARGV{oldstyle}     ? 'yes'     : 'no'     ]}
    proportional:       @{[ $ARGV{proportional} ? 'yes'     : 'no'     ]}
    tabular:            @{[ $ARGV{tabular}      ? 'yes'     : 'no'     ]}
    ts1:                @{[ $ARGV{textcomp}     ? 'yes'     : 'no'     ]}
    smallcaps:          @{[ $ARGV{smallcaps}    ? 'yes'     : 'no'     ]}
    swash:              @{[ $ARGV{swash}        ? 'yes'     : 'no'     ]}
    titling:            @{[ $ARGV{titling}      ? 'yes'     : 'no'     ]}
    superiors:          @{[ $ARGV{superiors}    ? 'yes'     : 'no'     ]}
    inferiors:          $ARGV{inferiors}
    ornaments:          @{[ $ARGV{ornaments}    ? 'yes'     : 'no'     ]}
    fractions:          @{[ $ARGV{fractions}    ? 'yes'     : 'no'     ]}
    ligatures:          @{[ $ARGV{ligatures}    ? 'yes'     : 'no'     ]}

    target:             $ARGV{target}
    extra:              $ARGV{extra}

    figurekern:         @{[ $ARGV{figurekern} ? 'keep' : 'remove' ]}

    nfssweight:         @{[ join q{, }, @{$ARGV{nfssweight}} ]}
    nfsswidth:          @{[ join q{, }, @{$ARGV{nfsswidth}}  ]}

    math:               @{[ $ARGV{math} ? 'yes' : 'no' ]}
    mathspacing:        $ARGV{mathspacing}

    fontname suffix:    @{[ $ARGV{t1suffix} || '(none)' ]}

END_ARGUMENTS

    if ($ARGV{fig_height} or $ARGV{fig_width}) {
        print {$self} <<"END_FIGURE_DEFAULTS";
    default figures:    @{[
                            $ARGV{fig_width}  eq 'pnum' ? 'proportional'
                                :                         'tabular'
                        ]} @{[
                            $ARGV{fig_height} eq 'onum' ? 'oldstyle'
                                :                         'lining'
                        ]}

END_FIGURE_DEFAULTS
    }

    if ($ARGV{dryrun}) {
        print {$self} "    DRY RUN\n\n";
    }

    return;
}


# --------------------------------------------------------------------------
#   Logs command line options and the results of font info parsing.
# --------------------------------------------------------------------------
sub log_parsing {
    my ($self, $fontlist) = @_;

    print {$self} '-' x 76 . "\n\n" . "Results of font info parsing:\n";

    for my $font (@{$fontlist}) {
        print {$self} <<"END_PARSE_FONT";

    $font->{filename}
        Name:       $font->{name}
        Family:     $font->{family}
        Subfamily:  $font->{subfamily}
        Weight:     $font->{weight} ($font->{weight_class})
        Width:      $font->{width} ($font->{width_class})
        Shape:      $font->{shape} @{[ $font->{is_smallcaps}
                                            ? 'smallcaps' : '' ]}
        Size:       $font->{minsize}-$font->{maxsize}
        Features:   @{[ join q(, ), sort keys %{$font->{feature}} ]}
END_PARSE_FONT
    }

    return;
}


# --------------------------------------------------------------------------
#   Logs the mapping of NFSS codes to weights and widths.
# --------------------------------------------------------------------------
sub log_nfss_mapping {
    my ($self, $nfss_mapping) = @_;

    print {$self} "\n" . '-' x 76 . "\n\nNFSS mappings:\n\n";
    for my $weight (Attr::get_all_nfss_weights()) {
        printf {$self} "    %-3s =>  %s\n",
                       $weight || 'm',
                       $nfss_mapping->{weight}{$weight}[0] || '';
    }
    printf {$self} "\n";
    for my $width (Attr::get_all_nfss_widths()) {
        printf {$self} "    %-3s =>  %s\n",
                       $width || 'm',
                       $nfss_mapping->{width}{$width}[0] || '';
    }

    return;
}


# --------------------------------------------------------------------------
#   Logs all fonts we're going to create.
# --------------------------------------------------------------------------
sub log_worklist {
    my ($self, $worklist) = @_;

    my @workitems
        = sort { $a->{font}{filename}    cmp $b->{font}{filename}
                    || $a->{encoding}    cmp $b->{encoding}
                    || $a->{figurestyle} cmp $b->{figurestyle}
               }
               @{$worklist};

    my $prevfn = q{};
    for my $workitem (@workitems) {
        if ($prevfn ne $workitem->{font}{filename}) {
            print {$self} <<"END_FONTINFO";

    ------------------------------------------------------------------------

    $workitem->{font}{filename}

        Generating these encodings, figure styles and shapes:

            ENC     STYLE   SHAPE   FEATURES USED

END_FONTINFO
        }
        printf {$self} "            %-3s     %-4s    %-4s    %s\n",
                       $workitem->{encoding},
                       $workitem->{figurestyle},
                       $workitem->{fdshape},
                       join(q{, }, @{$workitem->{features}});
        $prevfn  = $workitem->{font}{filename};
    }

    return;
}


# --------------------------------------------------------------------------
#   Logs all generated otftotfm commands.
# --------------------------------------------------------------------------
sub log_commands {
    my ($self, $commandlist) = @_;

    print {$self} "\n\n";
    print {$self} join "\n\n", @{$commandlist};
    print {$self} "\n";

    return;
}


############################################################################


package Options;

my $USAGE =<<'END_USAGE';

'autoinst' is a wrapper around Eddie Kohler's TypeTools
(http://www.lcdf.org/type/), for installing OpenType fonts in LaTeX.

Usage: autoinst [options] font[s]

Possible options:
    -encoding=ENC[,ENC]*    Specify text encoding(s) (default: OT1,LY1,T1)

    -(no)lining             Toggle creation of lining digits
    -(no)oldstyle           Toggle creation of oldstyle digits
    -(no)proportional       Toggle creation of proportional digits
    -(no)tabular            Toggle creation of tabular digits
    -(no)ts1                Toggle creation of TS1 fonts
    -(no)smallcaps          Toggle creation of smallcaps
    -(no)swash              Toggle creation of swash
    -(no)titling            Toggle creation of titling
    -(no)superiors          Toggle creation of fonts with superior characters
    -noinferiors
    -inferiors=[none|auto|subs|sinf|dnom]
                            Use this style for subscripts (see docs)
    -(no)ornaments          Toggle creation of ornament fonts
    -(no)fractions          Toggle creation of fonts with digits for fractions
    -(no)ligatures          Toggle manual addition of f-ligatures to font

    -serif                  Install font as serif font
    -sanserif               Install font as sanserif font
    -typewriter             Install font as typewriter font

    -defaultlining
    -defaultoldstyle        Specify which figure style should be
    -defaulttabular             considered 'default' for this font; see docs
    -defaultproportional

    -extra="EXTRA"          Add EXTRA to the otftotfm command for all fonts
    -target="DIRECTORY"     Install files into specified TEXMF tree
    -vendor="VENDOR"        Only used for naming directories
    -typeface="TYPEFACE"    Only used for naming directories

    -(no)figurekern         Keep or remove kerns between tabular figures

    -nfssweight=XX=YYYY     Map the "XX" NFSS code to the "YYYY" weight
    -nfsswidth=XX=YYYY      Map the "XX" NFSS code to the "YYYY" width

    -help                   Print this text and exit
    -doc                    Print the complete documentation and exit
    -dryrun                 Don't generate fonts, only log what would be done
    -logfile="FILE"         Write log to "FILE" (default: <fontfamily>.log)
    -verbose                Print more data to log file
    -version                Print version number and exit

    -math                   Generate basic math fonts
    -mathspacing=AMOUNT     Letterspace the math fonts by AMOUNT/1000 em

    -t1suffix=SUFFIX        Add SUFFIX to name of generated pfb fonts

    font[s]                 The fonts (.otf or .ttf format) to install.

Please report any bugs or suggestions to <marcpenninga@gmail.com>.
END_USAGE

# Default values for the command-line arguments.
%ARGV = (
    encoding        => 'OT1,LY1,T1',
    textcomp        => '2',     # 0 = no, 1 = yes, 2 = ('T1' ? yes : no)
    lining          => '1',     # 0 = no, 1 = yes
    oldstyle        => '1',     # 0 = no, 1 = yes
    proportional    => '1',     # 0 = no, 1 = yes
    tabular         => '1',     # 0 = no, 1 = yes
    smallcaps       => '1',     # 0 = no, 1 = yes
    swash           => '1',     # 0 = no, 1 = yes
    titling         => '1',     # 0 = no, 1 = yes
    superiors       => '1',     # 0 = no, 1 = yes
    inferiors       => 'none',  # values: none, auto, subs, sinf, dnom
    ornaments       => '1',     # 0 = no, 1 = yes
    fractions       => '0',     # 0 = no, 1 = yes
    ligatures       => '2',     # 0 = no, 1 = yes, 2 = ('tt' ? no : yes)
    nfss            => '',
    fig_height      => '',
    fig_width       => '',
    extra           => '',
    target          => '',
    vendor          => 'lcdftools',
    typeface        => '',
    dryrun          => '0',     # 0 = no, 1 = yes
    logfile         => '',
    figurekern      => '1',     # 0 = no, 1 = yes
    verbose         => 0,
    nfsswidth       => [],
    nfssweight      => [],
    math            => 0,
    mathspacing     => 0,
    t1suffix        => 'none',
);


# --------------------------------------------------------------------------
#   Parses the command-line options and removes these from @ARGV.
# --------------------------------------------------------------------------
sub parse_options {
    $ARGV{cmdline} = join ' ', ($0, @ARGV);

    Getopt::Long::GetOptions(
        'help|?'              =>  sub { print $USAGE; exit },
        'version'             =>  sub { exit },
        'doc'                 =>  sub { Pod::Usage::pod2usage(-verbose => 2) },
        'encoding=s'          => \$ARGV{encoding},
        'ts1!'                => \$ARGV{textcomp},
        'lining!'             => \$ARGV{lining},
        'oldstyle!'           => \$ARGV{oldstyle},
        'proportional!'       => \$ARGV{proportional},
        'tabular!'            => \$ARGV{tabular},
        'smallcaps!'          => \$ARGV{smallcaps},
        'swash!'              => \$ARGV{swash},
        'titling!'            => \$ARGV{titling},
        'superiors!'          => \$ARGV{superiors},
        'noinferiors'         =>  sub { $ARGV{inferiors} = 'none' },
        'inferiors:s'         => \$ARGV{inferiors},
        'ornaments!'          => \$ARGV{ornaments},
        'fractions!'          => \$ARGV{fractions},
        'ligatures!'          => \$ARGV{ligatures},
        'serif'               =>  sub { $ARGV{nfss} = 'rm' },
        'sanserif'            =>  sub { $ARGV{nfss} = 'sf' },
        'typewriter'          =>  sub { $ARGV{nfss} = 'tt' },
        'defaultlining'       =>  sub { $ARGV{fig_height} = 'lnum' },
        'defaultoldstyle'     =>  sub { $ARGV{fig_height} = 'onum' },
        'defaulttabular'      =>  sub { $ARGV{fig_width}  = 'tnum' },
        'defaultproportional' =>  sub { $ARGV{fig_width}  = 'pnum' },
        'extra=s'             => \$ARGV{extra},
        'target=s'            => \$ARGV{target},
        'vendor=s'            => \$ARGV{vendor},
        'typeface=s'          => \$ARGV{typeface},
        'dryrun'              => \$ARGV{dryrun},
        'figurekern!'         => \$ARGV{figurekern},
        'logfile=s'           => \$ARGV{logfile},
        'verbose+'            => \$ARGV{verbose},
        'nfssweight=s%'       => sub {
                                     my ($ignored, $key, $values) = @_;
                                     $key = lc $key;
                                     push @{$ARGV{nfssweight}},
                                          "$key=$values";
                                     my @values = split m/,/, lc $values;
                                     $key = q{} if $key eq 'm';
                                     Attr::set_weight($key, @values);
                                     $ARGV{$key} = 'user-defined';
                                 },
        'nfsswidth=s%'        => sub {
                                     my ($ignored, $key, $values) = @_;
                                     $key = lc $key;
                                     my @values = split m/,/, lc $values;
                                     push @{$ARGV{nfsswidth}},
                                          "$key=$values";
                                     $key = q{} if $key eq 'm';
                                     Attr::set_width($key, @values);
                                     $ARGV{$key} = 'user-defined';
                                 },
        'math!'               => \$ARGV{math},
        'mathspacing=i'       => \$ARGV{mathspacing},
        't1suffix:s'          => \$ARGV{t1suffix},
    )
    or die "$USAGE";

    if (!@ARGV) {
        Pod::Usage::pod2usage(
            -msg => '[ERROR]     No font files given, nothing to do!',
            -verbose => 1);
    }

    return;
}


############################################################################


package Otftotfm;

# --------------------------------------------------------------------------
#   Returns a string with all "directory" options for otftotfm set.
#   Also creates directories that don't exist yet.
# --------------------------------------------------------------------------
sub get_targetdirs {
    my ($family, $fontlist) = @_;

    my %has_fonttype = map { ($_->{fonttype} => 1) } @{$fontlist};

    my @filetypes = qw(tfm vf);
    if ($has_fonttype{opentype}) { push @filetypes, qw(type1) }
    if ($has_fonttype{truetype}) { push @filetypes, qw(truetype) }

    my %dir = map { ( $_ => File::Spec->catdir(
                                $ARGV{target},
                                'fonts',
                                $_,
                                $ARGV{vendor},
                                $ARGV{typeface} || $family) )
                  }
                  @filetypes;

    $dir{$_}
        = File::Spec->catdir(
            $ARGV{target}, 'fonts', $_, 'dvips', $ARGV{typeface} || $family)
        for qw(enc map);

    File::Path::make_path(values %dir) unless $ARGV{dryrun};

    my $result
        = join q{ },
               map { qq(--${_}-directory="$dir{$_}") }
                   @filetypes;
    $result .= qq( --encoding-directory="$dir{enc}" --map-file=")
               . File::Spec->catfile($dir{map}, "$family.map")
               . '"';

    return $result;
}


# The official names for various coding schemes.
my %SCHEME = (
    OT1 => 'TEX TEXT',
    OML => 'TEX MATH ITALIC',
    T1  => 'EXTENDED TEX FONT ENCODING - LATIN',
    TS1 => 'TEX TEXT COMPANION SYMBOLS 1---TS1',
    LY1 => 'TEX TYPEWRITER AND WINDOWS ANSI',
    LGR => 'GREEK FONT ENCODING - LGR',
    T2A => 'TEX CYRILLIC FONT ENCODING - T2A',
    T2B => 'TEX CYRILLIC FONT ENCODING - T2B',
    T2C => 'TEX CYRILLIC FONT ENCODING - T2C',
    T3  => 'TEX IPA ENCODING',
    TS3 => 'TEX IPA SYMBOL ENCODING',
);

# --------------------------------------------------------------------------
#   Generates a command for otftotfm from a work item.
# --------------------------------------------------------------------------
sub create_command {
    my ($workitem, $targetdirs) = @_;

    my $want_ligkerns
        = ( $ARGV{ligatures} == 1 )
            || Util::any( map { $_ eq 'liga' } @{$workitem->{features}} );

    return join q( ), 'otftotfm',
                      '--automatic',
                      "--encoding='$workitem->{enc_file}'",
                      $targetdirs,
                      '--no-updmap',
                      '--force',
                      ($SCHEME{$workitem->{encoding}}
                         ? qq(--coding-scheme="$SCHEME{$workitem->{encoding}}")
                         : q()),
                      (map { "--feature=$_" } @{$workitem->{features}}),
                      ($want_ligkerns
                         ? ( '--ligkern="f i =: fi"',
                             '--ligkern="f l =: fl"',
                             '--ligkern="f f =: ff"',
                             '--ligkern="ff i =: ffi"',
                             '--ligkern="ff l =: ffl"' )
                         : q()),
                      Tables::get_extra($workitem->{figurestyle}),
                      Tables::get_extra($workitem->{style}),
                      $ARGV{extra},
                      qq("$workitem->{font}{filename}"),
                      $workitem->{fontname},
                      ;
}


# --------------------------------------------------------------------------
#   Executes all commands.
# --------------------------------------------------------------------------
sub run_commands {
    my ($commandlist, $family, $log) = @_;

    my $oops = 0;
    $| = 1;     # turn on autoflush, to make a poor man's progress bar
    print "[INFO]      Generating fonts for $family ";
    for my $command (@{$commandlist}) {
        print '.';
        open my $otftotfm, '-|', "$command 2>&1"
            or die "could not fork(): $!";
        my $msgs = do { local $/; <$otftotfm> };
        close $otftotfm
            or do {
            warn "\n$command\n\n$msgs\n";
            $log->log("\n$command\n\n$msgs\n");
            $oops = 1;
        };
    }
    print "\n";
    $| = 0;
    if ($oops) {
        warn <<"END_OTFTOTFM_WARNING";
[ERROR]     One or more calls to 'otftotfm' returned a non-zero status code;
            please check the messages above and in the log file.
END_OTFTOTFM_WARNING
    }

    return;
}


############################################################################


package Tables;

=begin Comment

    The %STYLE table is used in deciding which font styles
    (normal, small caps, swash or textcomp) to generate.

    Each key in this table names a style; the corresponding value
    is an anonymous hash with several key/value pairs:
        code    An anonymous hash with three possible keys:
                'n'  -> the NFSS code to use for this variant shape
                        if the 'basic shape' is upright;
                'it' -> the NFSS code to use for this variant shape
                        if the 'basic shape' is italic
                'sl' -> the NFSS code to use for this variant shape
                        if the 'basic shape' is slanted (aka oblique);
                If any entry is missing, the corresponding version
                of this variant style will not be built.
        reqd    A list of required OpenType features;
                this style is built if the font supports at least *one*
                of these features.
        nice    A list of optional OpenType features;
                these are used if the font supports them, but don't
                prevent this style from being built when missing.
        extra   Extra options passed to otftotfm when creating this style.
        name    A string added to the name of the generated font,
                to make it unique.

    Textcomp is treated as a 'style' even though it is technically
    an encoding; that is just the easiest way to do things.

=end Comment

=cut

my %STYLE = (
    normal => {
        code  => { n => 'n', it => 'it', sl => 'sl' },
        reqd  => [],
        nice  => [],
        extra => '',
        name  => '',
    },
    smallcaps => {
        code  => { n => 'sc', it => 'scit', sl => 'scsl' },
        reqd  => [ 'smcp' ],
        nice  => [],
        extra => '--unicoding="germandbls =: SSsmall" --unicoding="ff =: FFsmall" --unicoding="fi =: FIsmall" --unicoding="ffi =: FFIsmall" --unicoding="fl =: FLsmall" --unicoding="ffl =: FFLsmall"',
        name  => 'sc',
    },
    swash => {
        code  => { n => 'nw', it => 'sw' },
        reqd  => [ 'swsh' ],
        nice  => [ 'dlig' ],
        extra => '--include-alternates="*.swash"',
        name  => 'swash',
    },
    textcomp => {
        code  => { n => 'n', it => 'it', sl => 'sl' },
        reqd  => [],
        nice  => [ 'onum' ],
        extra => '',
        name  => '',
    },
    math => {
        code  => { n => 'n', it => 'it', sl => 'sl' },
        reqd  => [],
        nice  => [ 'onum' ],
        extra => '--math-spacing=127',
        name  => '',
    },
);

=begin Comment

    The %FIGURESTYLE table is used in deciding which figure styles to generate.
    Each figure style (lining, oldstyle, tabular, proportional, superior,
    inferior etc.) becomes a separate font family. We also treat Ornaments
    as a figure style here; that's just the easiest way to handle them.

    Each key in this table names a figure style; the corresponding
    value is an anonymous hash with four key/value pairs:
        reqd    A list of required OpenType features; this style is built
                if the font supports *all* these features.
        nice    A list of optional OpenType features;
                these are used if the font supports them, but don't
                prevent this style from being built when missing.
        extra   Extra options passed to otftotfm when creating this style.
        style   An anonymous array of 'variant' styles to build with
                this figure style.

    The 'reqd' and 'nice' subtables for the TLF, LF, TOsF and OsF styles
    are empty; these are filled in at run time, depending on
    which figure style is default for the current font.

    The 'reqd' subtable for the Inf style is also empty; this may be filled
    with 'subs', 'sinf' or 'dnom' depending on the -inferiors options.

=end Comment

=cut

my %FIGURESTYLE = (
    TLF => {
        reqd   => [],
        nice   => [ 'kern', 'liga' ],
        extra  => '',
        styles => [ qw(normal smallcaps swash textcomp math) ],
    },
    LF => {
        reqd   => [],
        nice   => [ 'kern', 'liga' ],
        extra  => '',
        styles => [ qw(normal smallcaps swash textcomp math) ],
    },
    TOsF => {
        reqd   => [],
        nice   => [ 'kern', 'liga' ],
        extra  => '',
        styles => [ qw(normal smallcaps swash textcomp math) ],
    },
    OsF => {
        reqd   => [],
        nice   => [ 'kern', 'liga' ],
        extra  => '',
        styles => [ qw(normal smallcaps swash textcomp math) ],
    },
    Sup => {
        reqd   => [ 'sups' ],
        nice   => [],
        extra  => '--ligkern="* {KL} *"',
        styles => [ 'normal' ],
    },
    Inf => {
        reqd   => [],
        nice   => [],
        extra  => '--ligkern="* {KL} *"',
        styles => [ 'normal' ],
    },
    Numr => {
        reqd   => [ 'numr'],
        nice   => [],
        extra  => '--ligkern="* {KL} *"',
        styles => [ 'normal' ],
    },
    Dnom => {
        reqd   => [ 'dnom' ],
        nice   => [],
        extra  => '--ligkern="* {KL} *"',
        styles => [ 'normal' ],
    },
    Titl => {
        reqd   => [ 'titl' ],
        nice   => [ 'kern', 'liga' ],
        extra  => '',
        styles => [ 'normal' ],
    },
    Orn => {
        reqd   => [ 'ornm' ],
        nice   => [],
        extra  => '--ligkern="* {KL} *"',
        styles => [ 'normal' ],
    },
);


# --------------------------------------------------------------------------
#   Getter; returns a list of all known figure styles.
# --------------------------------------------------------------------------
sub get_all_figurestyles {
    return keys %FIGURESTYLE;
}


# --------------------------------------------------------------------------
#   Getter; returns all styles to generate for the given figure style.
# --------------------------------------------------------------------------
sub get_styles {
    my $figurestyle = shift;

    return grep { defined $STYLE{$_} }
                @{$FIGURESTYLE{$figurestyle}{styles}};
}


# --------------------------------------------------------------------------
#   Getter; returns a list of req'd features for the given (figure) style.
# --------------------------------------------------------------------------
sub get_reqd_features {
    my $what = shift;

    my $result = $FIGURESTYLE{$what}{reqd} // $STYLE{$what}{reqd} // [];

    return @{$result};
}


# --------------------------------------------------------------------------
#   Getter; returns a list of add'l features for the given (figure) style.
# --------------------------------------------------------------------------
sub get_nice_features {
    my $what = shift;

    my $result = $FIGURESTYLE{$what}{nice} // $STYLE{$what}{nice} // [];

    return @{$result};
}


# --------------------------------------------------------------------------
#   Getter; returns a list of all features for the given (figure) style.
# --------------------------------------------------------------------------
sub get_features {
    my $what = shift;

    return ( get_reqd_features($what), get_nice_features($what) );
}


# --------------------------------------------------------------------------
#   Getter; returns the name of the given style.
# --------------------------------------------------------------------------
sub get_name {
    my $what = shift;

    return $STYLE{$what}{name} // '';
}


# --------------------------------------------------------------------------
#   Getter; returns the 'extra' arguments for the given (figure) style.
# --------------------------------------------------------------------------
sub get_extra {
    my $what = shift;

    return $FIGURESTYLE{$what}{extra} // $STYLE{$what}{extra} // '';
}


# --------------------------------------------------------------------------
#   Getter; returns the NFSS code for the given style and 'basic' shape.
# --------------------------------------------------------------------------
sub get_fdshape {
    my ($style, $basicshape) = @_;

    return $STYLE{$style}{code}{$basicshape};
}


# --------------------------------------------------------------------------
#   Processes the command-line options. This is split into a number
#   of smaller steps, that each process a group of related options.
# --------------------------------------------------------------------------
sub process_options {
    process_styles_options();
    process_encoding_options();
    process_target_options();
    process_output_options();

    return;
}


# --------------------------------------------------------------------------
#   Processes all options that select or deselect styles.
# --------------------------------------------------------------------------
sub process_styles_options {
    delete $STYLE{smallcaps}           unless $ARGV{smallcaps};
    delete $STYLE{swash}               unless $ARGV{swash};

    delete $FIGURESTYLE{Titl}          unless $ARGV{titling};
    delete $FIGURESTYLE{Sup}           unless $ARGV{superiors};
    delete $FIGURESTYLE{Orn}           unless $ARGV{ornaments};
    delete @FIGURESTYLE{qw(Numr Dnom)} unless $ARGV{fractions};
    $ARGV{inferiors} ||= 'auto';
    if    ($ARGV{inferiors} eq 'none') { delete $FIGURESTYLE{Inf} }
    elsif ($ARGV{inferiors} eq 'auto') { $FIGURESTYLE{Inf}{reqd} = ['auto'] }
    elsif ($ARGV{inferiors} eq 'subs') { $FIGURESTYLE{Inf}{reqd} = ['subs'] }
    elsif ($ARGV{inferiors} eq 'sinf') { $FIGURESTYLE{Inf}{reqd} = ['sinf'] }
    elsif ($ARGV{inferiors} eq 'dnom') { $FIGURESTYLE{Inf}{reqd} = ['dnom'] }
    else  {
        # Apparently we mistook the first argument (font name) for
        # an optional argument to -inferiors; let's undo that.
        unshift @ARGV, $ARGV{inferiors};
        $ARGV{inferiors} = 'auto';
        $FIGURESTYLE{Inf}{reqd} = ['auto'];
    }

    # Fix the %FIGURESTYLE table to take 'default' figure styles into account.
    if ($ARGV{fig_height} eq 'onum') {
        push @{$FIGURESTYLE{TLF}{reqd}},  'lnum';
        push @{$FIGURESTYLE{LF}{reqd}},   'lnum';
        push @{$FIGURESTYLE{TOsF}{nice}}, 'onum';
        push @{$FIGURESTYLE{OsF}{nice}},  'onum';
    }
    else {
        push @{$FIGURESTYLE{TLF}{nice}},  'lnum';
        push @{$FIGURESTYLE{LF}{nice}},   'lnum';
        push @{$FIGURESTYLE{TOsF}{reqd}}, 'onum';
        push @{$FIGURESTYLE{OsF}{reqd}},  'onum';
    }

    if ($ARGV{fig_width} eq 'pnum') {
        push @{$FIGURESTYLE{TLF}{reqd}},  'tnum';
        push @{$FIGURESTYLE{TOsF}{reqd}}, 'tnum';
        push @{$FIGURESTYLE{LF}{nice}},   'pnum';
        push @{$FIGURESTYLE{OsF}{nice}},  'pnum';
    }
    else {
        push @{$FIGURESTYLE{TLF}{nice}},  'tnum';
        push @{$FIGURESTYLE{TOsF}{nice}}, 'tnum';
        push @{$FIGURESTYLE{LF}{reqd}},   'pnum';
        push @{$FIGURESTYLE{OsF}{reqd}},  'pnum';
    }

    delete @FIGURESTYLE{qw(LF TLF)}    unless $ARGV{lining};
    delete @FIGURESTYLE{qw(OsF TOsF)}  unless $ARGV{oldstyle};
    delete @FIGURESTYLE{qw(LF OsF)}    unless $ARGV{proportional};
    delete @FIGURESTYLE{qw(TLF TOsF)}  unless $ARGV{tabular};

    if (!$ARGV{figurekern}) {
        my @digits = qw(zero one two three four five six seven eight nine);
        my $tkern
            = join ' ', map { my $left = $_;
                              map { qq(--ligkern="$left {} $_") } @digits
                            }
                            @digits;

        $FIGURESTYLE{TLF}{extra}  = $tkern;
        $FIGURESTYLE{TOsF}{extra} = $tkern;
    }

    return;
}


# --------------------------------------------------------------------------
#   Processes the options for selecting encodings.
# --------------------------------------------------------------------------
sub process_encoding_options {

    # All specified encodings should either be built-in,
    # or have an accompanying .enc file in the current directory.
    my @encodings = split /,/, $ARGV{encoding};
    for my $enc (@encodings) {
        if ($enc !~ m/\A(OT1|T1|TS1|LY1|LGR|T2[ABC]|T3|TS3)\z/xmsi) {
            my $try = $enc;
            $try .= '.enc' if $try !~ m/[.]enc\z/xmsi;
            if (!-e $try) {
                die "[ERROR]     No .enc file found for '$enc'";
            }
        }
    }
    my @textencodings = grep { $_ !~ m/TS1/xmsi } @encodings;
    $ARGV{encoding} = \@textencodings;

    # TS1-encoded fonts are generated if:
    # - the user explicitly asked for TS1, or
    # - the text encodings contain T1 and the user didn't turn off TS1
    if ($ARGV{textcomp} == 1
            or ($ARGV{textcomp} >= 1
                and grep { uc $_ eq 'T1' } @{$ARGV{encoding}})) {
        $ARGV{textcomp} = 1;
    }
    else {
        delete $STYLE{textcomp};
    }

    if ($ARGV{math}) {
        if (!( grep { $_ eq 'OT1' } @{$ARGV{encoding}} )) {
            $ARGV{encoding} = [ 'OT1', @{$ARGV{encoding}} ];
        }
    }
    else {
        delete $STYLE{math}
    }

    if ($ARGV{mathspacing}) {
        if (defined $STYLE{math}{extra}) {
            $STYLE{math}{extra} .= " --letterspacing=$ARGV{mathspacing}";
        }
    }

    return;
}


# --------------------------------------------------------------------------
#   Processes the options related to the target TEXMF directory.
# --------------------------------------------------------------------------
sub process_target_options{

    my $localtarget = File::Spec->catdir( Cwd::getcwd(), 'autoinst_output' );
    if (!$ARGV{target}) {
        my $is_windows_os = ( $^O =~ /^MSWin/i );
        my $kpsepath = $is_windows_os
            ? eval { qx( kpsewhich -expand-var=\$TEXMFLOCAL;\$TEXMFHOME ) }
            : eval { qx( kpsewhich -expand-var='\$TEXMFLOCAL:\$TEXMFHOME' ) }
            ;
        if (!$kpsepath) {
            warn <<"END_WARNING_KPSEWHICH";
[WARNING]   Call to "kpsewhich" failed.
            Maybe your TeX system doesn't use the kpathsea library?

            Consider using the "-target" command line option
            to specify a TEXMF tree where autoinst should install all files.
END_WARNING_KPSEWHICH
        }
        else {
            my $pathsep = $is_windows_os ? ';' : ':';
            for my $dir ( split m/$pathsep/xms, substr $kpsepath, 0, -1 ) {
                if (-w $dir) { $ARGV{target} = $dir; last }
                if (-e $dir) { next }
                my $par = File::Spec->catdir( $dir, File::Spec->updir() );
                if (-w $par) { $ARGV{target} = $dir; last }
            }
        }
    }

    if (!$ARGV{target}) {
        $ARGV{target} = $localtarget;
        warn <<"END_WARNING_DUMPING_FILES";
[WARNING]   No user-writable TEXMF-tree found!

            I'm putting all generated files in "$ARGV{target}".

            Please install these files into a suitable TEXMF directory,
            update the filename database and run 'updmap' (or similar);
            see your TeX installation's documentation.
END_WARNING_DUMPING_FILES
    }

    if ($ARGV{target} =~ m/\s/xms) {
        warn <<"END_WARNING_SPACES_IN_PATHS";
[WARNING]   The pathname of your target directory contains spaces:
                "$ARGV{target}"
            If you experience any problems, try re-running autoinst
            on a target directory without spaces in its name.
END_WARNING_SPACES_IN_PATHS
    }

    return;
}


# --------------------------------------------------------------------------
#   Processes the output related options.
# --------------------------------------------------------------------------
sub process_output_options{
    # If the user gave -t1suffix *without* value as the last option,
    # Getopt::Long may mistake the next argument (a font filename)
    # for the value of -t1suffix; we take care of this case
    # by testing whether the value refers to an existing file
    # and repairing things if necessary.
    if (-e $ARGV{t1suffix}) {
        unshift @ARGV, $ARGV{t1suffix};
        $ARGV{t1suffix} = '';
    }

    $ARGV{t1suffix} ||= 'PS';

    if ($ARGV{t1suffix} eq 'none') {
        $ARGV{t1suffix} = '';
    }

    return;
}


# --------------------------------------------------------------------------
#   Processes command line options with font family-specific defaults.
# --------------------------------------------------------------------------
sub process_family_dependent_options {
    my $fontlist = shift;

    if (!$ARGV{nfss}) {
        $ARGV{nfss} = $fontlist->[0]{nfss};
    }
    # If the user didn't explicitly say anything about ligatures,
    # activate them unless the font is a typewriter font.
    if ($ARGV{ligatures} == 2 and $ARGV{nfss} eq 'tt') {
        $ARGV{ligatures} = 0;
    }

    # We can only handle the '-inferiors=auto' option now;
    # since we need to know which inferior figures this font supports,
    # we have to do the font info parsing first.
    if ($ARGV{inferiors} eq 'auto') {
        choose_inferiors($fontlist);
    }

    $ARGV{logfile} ||= sprintf "%s.log", lc $fontlist->[0]{family};

    return;
}


# --------------------------------------------------------------------------
#   Processes the -inferiors=auto option, given a list of fonts.
#   We look through these fonts and simply pick the very first
#   type of inferiors we see (we assume that this type is supported
#   by all fonts in this family).
# --------------------------------------------------------------------------
sub choose_inferiors {
    my $fontlist = shift;

    FONT:
    for my $font (@{$fontlist}) {
        for my $inf (qw(sinf subs dnom)) {
            if (exists $font->{feature}{$inf}) {
                $ARGV{inferiors} = "auto (-> $inf)";
                $FIGURESTYLE{Inf}{reqd} = [$inf];
                last FONT;
            }
        }
    }

    # If we didn't find any inferior figures,
    # delete the 'Inf' entry from the %FIGURESTYLE table
    # to indicate we don't want to generate this style.
    if ($ARGV{inferiors} eq 'auto') {
        delete $FIGURESTYLE{Inf};
        $ARGV{inferiors} = "auto (-> none)";
    }

    return;
}


############################################################################


package Util;

# --------------------------------------------------------------------------
#   Tests if all given predicates are true.
# --------------------------------------------------------------------------
sub all {
    return !( grep { !$_ } @_ );
}


# --------------------------------------------------------------------------
#   Tests if any of the given predicates are true.
# --------------------------------------------------------------------------
sub any {
    return grep { $_ } @_;
}


# --------------------------------------------------------------------------
#   Walks a (nested) dictionary and returns a lookup table with all keys.
# --------------------------------------------------------------------------
sub get_keys {
    my $dict = shift;
    my $seen = shift // {};

    while (my ($k, $v) = each %$dict) {
        $seen->{$k} = 1;
        get_keys($v, $seen) if ref $v eq 'HASH';
    }

    return $seen;
}


# --------------------------------------------------------------------------
#   Sorts its arguments so that longer strings come before shorter ones.
# --------------------------------------------------------------------------
sub sort_desc_length {
    return reverse sort { length($a) <=> length($b) } @_;
}


############################################################################


package Work;


# --------------------------------------------------------------------------
#   Decides which styles, figure styles and encodings to generate
#   for the given fonts.
# --------------------------------------------------------------------------
sub generate_worklist {
    my $fontlist = shift;

    my @worklist = map { { font => $_ } } @{$fontlist};

    #   1.  For each font, decide which figure styles should be created.
    @worklist = map { expand_figurestyles($_) } @worklist;

    #   2.  For each (font, figure style) combination,
    #       decide which styles should be created.
    @worklist = map { expand_styles($_) } @worklist;

    #   3.  For each (font, figure style, style) combination,
    #       decide which encodings should be created.
    @worklist = map { expand_encodings($_) } @worklist;

    #   4.  Some miscellaneous finishing touches.
    @worklist = grep { $_ } map { cleanup($_) } @worklist;

    return @worklist;
}


# --------------------------------------------------------------------------
#   Determines which figure styles to create for the given work item.
#   A figure style is created if the current font contains all of
#   the 'reqd' features for this figure style.
#   Returns a list of new work items, one for each figure style.
# --------------------------------------------------------------------------
sub expand_figurestyles {
    my $workitem = shift;

    my $font = $workitem->{font};

    my @results;
    for my $figurestyle (Tables::get_all_figurestyles()) {
        my @reqd = Tables::get_reqd_features($figurestyle);
        my $has_all_reqd = Util::all(map { $font->{feature}{$_} } @reqd);
        if ($has_all_reqd) {
            my %new_workitem = %{$workitem};
            $new_workitem{figurestyle} = $figurestyle;
            push @results, \%new_workitem;
        }
    }

    return @results;
}


# --------------------------------------------------------------------------
#   Determines which styles to create for the given work item.
#   A style is created if the current font has at least one of the
#   'reqd' features for this style, or if there are no 'reqd' features.
#   Returns a list of new work items, one for each style.
# --------------------------------------------------------------------------
sub expand_styles {
    my $workitem = shift;

    my ($font, $figurestyle) = @{$workitem}{qw(font figurestyle)};

    my @results;
    for my $style (Tables::get_styles($figurestyle)) {
        my @reqd = Tables::get_reqd_features($style);
        my $has_any_reqd
                = (scalar @reqd == 0)
                  || Util::any(map { $font->{feature}{$_} } @reqd);
        if ($has_any_reqd) {
            my %new_workitem = %{$workitem};
            $new_workitem{style} = $style;
            push @results, \%new_workitem;
        }
    }

    return @results;
}


# --------------------------------------------------------------------------
#   Determines which encodings to use for the given work item;
#   returns a list of new work items, one for each encoding.
# --------------------------------------------------------------------------
sub expand_encodings {
    my $workitem = shift;

    my ($font, $figurestyle, $style)
        = @{$workitem}{qw(font figurestyle style)};
    my @encodings = $style eq 'textcomp'  ? qw(ts1)
                  : $figurestyle eq 'Orn' ? qw(ly1)
                  : $style eq 'math'      ? qw(oml)
                  :                         @{$ARGV{encoding}}
                  ;

    my @results;
    for my $encoding (@encodings) {
        my %new_workitem = %{$workitem};
        $new_workitem{encoding} = $encoding;
        push @results, \%new_workitem;
    }

    return @results;
}


# --------------------------------------------------------------------------
#   Adds some miscellaneous finishing touches to the given work item.
# --------------------------------------------------------------------------
sub cleanup {
    my $workitem = shift;

    my ($font, $figurestyle, $style)
        = @{$workitem}{qw(font figurestyle style)};

    # Don't generate smallcaps version of TS1-encoded fonts,
    # as these contain the same glyphs as the regular version.
    if ($font->{is_smallcaps}) {
        if ($style eq 'textcomp') {
            return;
        }
        else {
            $style = 'smallcaps';
        }
    }

    # Look up the NFSS code for this font's shape...
    $workitem->{fdshape} = Tables::get_fdshape($style, $font->{basicshape});
    # ... but drop this workitem if we shouldn't generate this shape.
    if (!defined $workitem->{fdshape}) {
        return;
    }

    # Figure out whether the encoding option refers to a custom encoding file
    # in the current directory, or to the name of one of our standard
    # encodings.  In the latter case, we add the 'fontools_' prefix.
    my $try = $workitem->{encoding};
    $try .= '.enc' if $try !~ m/[.]enc\z/xmsi;
    if (-e $try) {
        $workitem->{enc_file} = $try;
        $workitem->{encoding}
            = File::Basename::basename($try, '.enc', '.ENC');
    }
    else {
        ($workitem->{enc_file} = $workitem->{encoding})
            =~ s{ \A (OT1|OML|T1|TS1|LY1|LGR|T2[ABC]|T3|TS3) \z }
                {fontools_\L$1\E}xmsi;
    }

    # Ornaments have no text encoding, and don't need kerning and ligatures.
    if ($figurestyle eq 'Orn') {
        $workitem->{encoding} = 'u';
    }

    # Compile list of OpenType features to use with this font.
    my %feature = map { ($_ => 1) }
                      grep { $font->{feature}{$_} }
                           ( Tables::get_features($figurestyle),
                             Tables::get_features($style) );
    if ($feature{lnum} && $feature{onum}) {
        delete $feature{lnum};
    }

    # Don't create ligatures if the user doesn't want them.
    delete $feature{liga} if !$ARGV{ligatures};

    # Don't create kerns and ligatures for symbol or math fonts.
    delete @feature{qw(kern liga)}
        if $workitem->{encoding} =~ m/\A ( TS\d | OML ) \z/xmsi;

    $workitem->{features} = [ sort keys %feature ];

    # Generate a unique name for this font.
    $workitem->{fontname}
            = join '-', grep { $_ } $font->{name},
                                    lc $figurestyle,
                                    lc Tables::get_name($style),
                                    lc $workitem->{encoding};

    $workitem->{encoding} = uc $workitem->{encoding};

    return $workitem;
}


# --------------------------------------------------------------------------
#   Modify the font and file names of all generated .pfb files.
# --------------------------------------------------------------------------
sub modify_fontnames {
    my ($family, $fontlist) = @_;

    my %has_fonttype = map { ($_->{fonttype} => 1) } @{$fontlist};
    return unless $has_fonttype{opentype};

    my $pfb_dir = File::Spec->catdir(
        $ARGV{target},
        'fonts',
        'type1',
        $ARGV{vendor},
        $ARGV{typeface} || $family);

    # The otftotfm-generated map file refers to the original otf files;
    # we need to change this to use our name-modified Type1 fonts instead.
    my $mapfile = File::Spec->catfile(
        $ARGV{target},
        'fonts',
        'map',
        'dvips',
        $ARGV{typeface} || $family,
        $family . '.map');
    open my $map, '<', $mapfile
        or die "[ERROR]     Cannot open '$mapfile' for reading";
    my $mapdata = do { local $/; <$map> };
    close $map;

    my $NOTICE = 'Converted to Type1 by autoinst/cfftot1; '
               . 'for use with pdfTeX only! ';

    my $newfam = $family . $ARGV{t1suffix};

    for my $font (@{$fontlist}) {
        next unless $font->{fonttype} eq 'opentype';

        my $full_family = $font->{originalfamily};
        if (index($full_family, $family) > -1) {
            $full_family = $family;
        }
        else {
            while ($full_family =~ m/[ ]/xms) {
                (my $no_space = $full_family) =~ s/[ ]+//xmsg;
                last if $no_space eq $family;
                $full_family =~ s/[ ]\S*\z//xms;
            }
            $full_family ||= $family;
        }
        my $newfullfam = $full_family . q( ) . $ARGV{t1suffix};

        my $newname = $font->{name};
        if ($newname =~ m/$family/xms) {
            $newname =~ s/$family/$newfam/xms;
        }
        else {
            $newname =~ s/(.+?)(-|\z)/$1$ARGV{t1suffix$2}/xms;
        }

        for my $suffix (q(), q(LCDFJ)) {
            my $oldfn = File::Spec->catfile(
                $pfb_dir, $font->{name} . $suffix . '.pfb');
            my $newfn = File::Spec->catfile(
                $pfb_dir, $newname . $suffix . '.pfb');

            next unless -e $oldfn;
            if ($suffix eq 'LCDFJ' and -z $oldfn) {
                unlink $oldfn;
                next;
            }

            my $cmd = qq(t1disasm "$oldfn");
            open my $t1disasm, '-|:raw', $cmd
                or die "[ERROR]     Could not fork(): $!";
            my @pfbdata = readline $t1disasm;
            close $t1disasm
                or die "[ERROR]     '$cmd' failed";

            for (@pfbdata) {
                if (m/%!PS-AdobeFont-1.0:[ ] | \/FontName[ ]/xms) {
                    s/$font->{name}/$newname/;
                }
                if (m/\/Notice[ ]/xms) {
                    s/[(]/($NOTICE/xms;
                }
                if (m/\/FullName[ ] | \/FamilyName[ ]/xms) {
                    s/$full_family/$newfullfam/
                        or s/(.+?)(-|\z)/$1$ARGV{t1suffix}$2/;
                }
            }

            $cmd = qq(t1asm --pfb >"$newfn");
            open my $t1asm, '|-:raw', $cmd
                or die "[ERROR]     Could not fork(): $!";
            print {$t1asm} @pfbdata;
            close $t1asm
                or die "[ERROR]     '$cmd' failed";

            unlink $oldfn unless $oldfn eq $newfn;

            $mapdata =~ s/$font->{name}$suffix.pfb/$newname$suffix.pfb/g;
        }
    }

    open $map, '>', $mapfile
        or die "[ERROR]     Cannot open '$mapfile' for writing";
    print {$map} $mapdata;
    close $map;

    return;
}


############################################################################


package main;

if ($RUNNING_AS_MAIN) {
    main();
}


__END__


############################################################################


    To create the documentation:

    pod2man --center='Marc Penninga' --release='fontools' --section=1 \
        autoinst - | groff -Tps -man - | ps2pdf - autoinst.pdf


=pod

=head1 NAME

autoinst - wrapper around the F<LCDF TypeTools>,
for installing and using OpenType fonts in LaTeX.


=head1 SYNOPSIS

B<autoinst> I<-help>

B<autoinst> [I<options>] B<font(s)>


=head1 DESCRIPTION

Eddie Kohler's I<LCDF TypeTools> are superb tools for installing
OpenType fonts in LaTeX, but they can be hard to use:
they need many, often long, command lines
and don't generate the F<fd> and F<sty> files LaTeX needs.
B<autoinst> simplifies the use of the I<TypeTools> for font installation
by generating and executing all commands for I<otftotfm>,
and by creating and installing all necessary F<fd> and F<sty> files.

Given a family of font files (in F<otf> or F<ttf> format),
B<autoinst> will create several LaTeX font families:

=over 2

=over 3

=item -

Four text families (with lining and oldstyle digits,
each in both tabular and proportional variants),
all with the following shapes:

=over 2

=over 8

=item I<n>

Roman (i.e., upright) text

=item I<it>, I<sl>

Italic and slanted (sometimes called oblique) text

=item I<sc>

Small caps

=item I<scit>, I<scsl>

Italic and slanted small caps

=item I<sw>

Swash

=item I<nw>

"Upright swash"

=back

=back

=item -

For each T1-encoded text family:
a family of TS1-encoded symbol fonts, in roman, italic and slanted shapes.

=item -

Families with superiors, inferiors, numerators and denominators,
in roman, italic and slanted shapes.

=item -

Families with "Titling" characters;
these "... replace the default glyphs
with corresponding forms designed specifically for titling.
These may be all-capital and/or larger on the body,
and adjusted for viewing at larger sizes"
(according to the OpenType Specification).

=item -

An ornament family; also in roman, italic and slanted shapes.

=back

=back

Of course, if your fonts don't contain italics, oldstyle digits, small caps
etc., the corresponding shapes and families are not created.
In addition, the creation of most families and shapes can be controlled
by the user (see L</COMMAND-LINE OPTIONS> below).

These families use the I<FontPro> project's naming scheme:
I<< <FontFamily>-<Suffix> >>, where I<< <Suffix> >> is:

=over 8

=item I<LF>

proportional (i.e., figures have varying widths) lining figures

=item I<TLF>

tabular (i.e., all figures have the same width) lining figures

=item I<OsF>

proportional oldstyle figures

=item I<TOsF>

tabular oldstyle figures

=item I<Sup>

superior characters (note that most fonts have only an incomplete set of
superior characters: digits, some punctuation and the letters I<abdeilmnorst>;
normal forms are used for other characters)

=item I<Inf>

inferior characters; usually only digits and some punctuation,
normal forms for other characters

=item I<Titl>

Titling characters; see above

=item I<Orn>

ornaments

=item I<Numr>, I<Dnom>

numerators and denominators

=back

The individual fonts are named I<< <FontName>-<suffix>-<shape>-<enc> >>,
where I<< <suffix> >> is the same as above (but in lowercase),
I<< <shape> >> is either empty, "sc" or "swash",
and I<< <enc> >> is the encoding (also in lowercase).
A typical name in this scheme would be I<FiraSans-Light-osf-sc-ly1>.


=head2 Using the fonts in your LaTeX documents

B<autoinst> generates a style file for using the fonts in LaTeX documents,
named F<< <FontFamily>.sty >>. This style file also loads the F<fontenc>
and F<textcomp> packages, if necessary.
To use the fonts, add the command C<<< \usepackage{I<< <FontFamily> >>} >>>
to the preamble of your document.

This style file has a few options:

=over 4

=item C<mainfont>

Redefine C<\familydefault> to make this font the main font
for the document.
This is a no-op if the font is installed as a serif font;
but if the font is installed as a sanserif or typewriter font,
this option saves you from having to redefine C<\familydefault>
yourself.

=item C<lining>, C<oldstyle>, C<tabular>, C<proportional>

Choose which figure style to use.
The defaults are "oldstyle" and "proportional" (if available).

=item C<<< scale=I<< <number> >> >>>, C<scale=MatchLowercase>

Scale the font by a factor of I<< <number> >>.
E.g., to increase the size of the font by 5%, use
C<<< \usepackage[scale=1.05]{I<< <FontFamily> >>} >>>.
The special value C<MatchLowercase> may be used to scale the font
so that its x-height matches that of the current main font
(which is usually Computer Modern Roman, unless you have loaded
another font package before this one).
The name C<scaled> may be used as a synonym for C<scale>.

=item C<medium>, C<book>, C<text>, C<normal>, C<regular>

Select the weight that LaTeX will use as the "regular" weight.

=item C<heavy>, C<black>, C<extrabold>, C<demibold>, C<semibold>, C<bold>

Select the weight that LaTeX will use as the "bold" weight.

=back

The last two groups of options will only work if
you have the F<mweights> package installed.
The default here is not to change LaTeX's default,
i.e. use the "m" and "b" weights.

The style file will also try to load the F<fontaxes> package
(on CTAN), which gives easy access to various font shapes and styles.
Using the machinery set up by F<fontaxes>, the generated style file
defines a number of commands (which take the text to be typeset as argument)
and declarations (which don't take arguments, but affect all text up to
the end of the current group) to access titling, superior and inferior
characters:


    DECLARATION     COMMAND         SHORT FORM OF COMMAND

    \tlshape        \texttitling    \texttl
    \supfigures     \textsuperior   \textsup, \textsu
    \inffigures     \textinferior   \textinf, \textin


In addition, the existing C<\swshape> and C<\textsw> commands are redefined
to place swash on F<fontaxes>' secondary shape axis (F<fontaxes> places it
on the primary shape axis) to make them behave properly when nested, so that
C<\swshape\upshape> will give upright swash.

There are no commands for accessing the numerator and denominator
fonts; these can be selected using F<fontaxes>' standard commands,
e.g., C<\fontfigurestyle{numerator}\selectfont>.

These commands are only generated for existing shapes and number styles;
no commands are generated for shapes and styles that are missing from
your fonts.
Also these commands are built on top of F<fontaxes>, so if that package
cannot be found, you're limited to using the lower-level commands from
standard NFSS (C<\fontfamily>, C<\fontseries>, C<\fontshape> etc.).

By default, B<autoinst> generates text fonts with OT1, LY1 and T1
encodings, and the generated style files use T1 as the default text encoding.
Other encodings can be chosen using the I<-encoding> option
(see L</COMMAND-LINE OPTIONS> below).


=head2 Maths

This is an experimental feature; B<USE AT YOUR OWN RISK!>
Test the results thoroughly before using them in real documents,
and be warned that future versions of B<autoinst> may introduce
incompatible changes.

The I<-math> option tells B<autoinst> to generate basic math fonts.
When enabled, the generated style file defines a few extra options
to access these math fonts:

=over 4

=item C<math>

Use these fonts for the maths in your document.

=item C<mathlining>, C<matholdstyle>

Choose which figure style to use in maths.
The default is "mathlining".

=item C<mathcal>

Use the swash characters from your fonts as the C<\mathcal> alphabet.
(This option will only exist if your fonts actually contain swash characters,
plus a C<swsh> feature to access them).

=item C<nomathgreek>

Don't redeclare greek letters in math.

=item C<<< math-style=I<< <style> >> >>>

Choose the "math style" to use.
With C<math-style=ISO>, all latin and greek letters in math are italic;
with C<math-style=TeX> (the default), uppercase greek is upright;
with C<math-style=french>, all greek as well as uppercase latin is upright;
and with C<math-style=upright> all letters are upright.

=back

Note that this C<math> option only affects digits, latin and greek letters,
plus a few basic punctuation characters; all other mathematical symbols,
operators, delimiters etc. are left as they were before.
If you don't want to use TeX's default versions of those symbols,
load another math package (such as F<mathdesign> or F<newtxmath>)
before loading the B<autoinst>-generated style file.

Finally, note that B<autoinst> doesn't check if your fonts actually contains
all of the required characters;
it just assumes that they do and sets up the style file accordingly.
Even if your fonts contain greek, characters such as C<\varepsilon>
may be missing.
You may also find that some glyphs I<are> present in your fonts,
but don't work well in equations or don't match with other symbols;
edit the generated style file to remove the declarations of
these offending characters.
Once again: test the results before using them!
If the characters themselves are fine but spaced too tightly,
you may try increasing the side bearings in math fonts with
the I<-mathspacing> option (see below), e.g. C<-mathspacing=50>.


=head2 NFSS codes

LaTeX's New Font Selection System (NFSS)
identifies fonts by a combination of family,
series (the concatenation of weight and width), shape and size.
B<autoinst> parses the font's metadata to determine these parameters.
When this fails (usually because the font family contains uncommon weights,
widths or shapes),
B<autoinst> ends up with multiple fonts having the same values
for these font parameters; such fonts cannot be used in NFSS,
since there's no way distinguish them.
When B<autoinst> detects such a situation, it will print an error message
and abort.
If that happens, either rerun B<autoinst> on a smaller set of fonts,
or add the missing widths, weights and shapes to the tables C<@WIDTH>,
C<@WEIGHT> and C<%SHAPE> in the source code.
Please also send a bug report (see L<AUTHOR> below).

The mapping of shapes to NFSS codes is done using the following table:

    SHAPE                               CODE
    --------------------------------    ----
    Roman, Upright                      n
    Italic                              it
    Oblique, Slant(ed), Incline(d)      sl

(I<Exception:> Adobe Silentium Pro contains two Roman shapes;
we map the first of these to C<n>, for the second one we (ab)use the C<it> code
as this family doesn't contain an Italic shape.)

For weights and widths, B<autoinst> tries to the standard NFSS codes
(ul, el, l, sl, m, sb, b, eb and ub for weights;
uc, ec, c, sc, m, sx, x, ex and ux for widths)
as much as possible.
Of course, not all 81 combinations of these NFSS weights and widths will map
to existing fonts;
and conversely it may not be possible to assign every existing font
a unique code in a sane way (especially for the weights,
some font families offer more variants than NFSS's codes can handle;
e.g., Fira Sans contains fifteen different weights!).
Therefore every font is also assigned a "series" name that is
the concatenation of its weight and width,
after expanding any abbreviations and converting to lowercase.
A font of "Cond" width and "Ultra" weight will then be known
as "ultrablackcondensed".

The exact mapping between fonts and NFSS codes can be found
in the generated F<fd> files and in the log file
(you may want to run B<autoinst> with the I<-dryrun> option
to check the chosen mapping beforehand).
The I<-nfssweight> and I<-nfsswidth> command-line options can be used
to finetune the mapping between NFSS codes and fonts.

To access specific weights or widths,
one can always use the C<\fontseries> command with the full series name
(i.e., C<\fontseries{demibold}\selectfont>).


=head2 Ornaments

Ornament fonts are regular LY1-encoded fonts, with a number of
"regular" characters replaced by ornament glyphs.
The OpenType specification says that fonts should only put their
ornaments in place of the lowercase ASCII letters, but some fonts
put them in other positions (such as those of the digits) as well.

Ornaments can be accessed like C<{\ornaments a}> and
C<{\ornaments\char"61}>, or equivalently
C<\textornaments{a}> and C<\textornaments{\char"61}>.
To see which ornaments a font contains (and at which positions),
run LaTeX on the file F<nfssfont.tex> (which is included in any
standard LaTeX installation), supply the name of the ornament font
(i.e., C<GaramondLibre-Regular-orn-u>) and give the command C<\table\bye>;
this will create a table of all glyphs in that font.

Note that versions of B<autoinst> up to 20200428 handled ornaments
differently, and fonts and style files generated by those versions
are not compatible with files generated by newer versions.


=head1 WARNINGS AND CAVEATS

=head2 OpenType fonts and licensing issues

Since F<pdfTeX> cannot subset otf-flavoured OpenType fonts,
I<otftotfm> will convert such fonts to Type1 (pfb) format.
However, many fonts (at least those licensed under the SIL Open Font License)
do not allow distributing such converted versions under their original name.

To meet these licensing requirements, B<autoinst> provides
a I<-t1suffix> command-line option that appends
a user-defined suffix to the names
(both the filename and the internal font name)
of all generated Type1 fonts; see L</COMMAND-LINE OPTIONS> below.


=head2 A note for MiKTeX users

Automatically installing the fonts into a suitable TEXMF tree
(as B<autoinst> tries to do by default) only works for TeX-installations
that use the F<kpathsea> library; with TeX distributions that implement
their own directory searching, such as MiKTeX, B<autoinst> will complain
that it cannot find the F<kpsewhich> program and move all generated files
into a subdirectory C<autoinst_output/> of the current directory.
If you use such a TeX distribution, you should either move these files
to their correct destinations by hand, or use the I<-target> option
(see L</COMMAND-LINE OPTIONS> below) to manually specify a TEXMF tree.

Also, some OpenType fonts contain so many kerning pairs that the resulting
F<pl> and F<vpl> files are too big for MiKTeX's F<pltotf> and F<vptovf>;
the versions that come with W32TeX (F<http://www.w32tex.org>)
and TeXLive (F<http://tug.org/texlive>) don't seem to have this problem.


=head2 A note for MacTeX users

By default, B<autoinst> will try to install all generated files into
the $TEXMFLOCAL tree; when this directory isn't user-writable,
it will use the $TEXMFHOME tree instead.  Unfortunately, MacTeX's version
of C<updmap-sys> doesn't search in $TEXMFHOME,
and hence MacTeX will not find the new fonts.

To remedy this, either run B<autoinst> as root (so that it can install
everything into $TEXMFLOCAL) or manually run C<updmap -user> to tell
TeX about the files in $TEXMFHOME.
This latter option does, however, come with some caveats;
see F<https://tug.org/texlive/scripts-sys-user.html>.



=head1 COMMAND-LINE OPTIONS

B<autoinst> tries hard to do The Right Thing (TM) by default,
so you usually won't need these options;
but most aspects of its operation can be fine-tuned if you want to.

You may use either one or two dashes before options,
and option names may be shortened to a unique prefix
(e.g., B<-encoding> may be abbreviated to B<-enc> or even B<-en>,
but B<-e> is ambiguous (it may mean either B<-encoding> or B<-extra>)).


=head2 General options

=over 4

=item B<-help>

Print a (relatively) short help text and exit.

=item B<-dryrun>

Don't generate output; just parse input fonts and write
the results to the log file.

=item B<-verbose>

Add more details to the log file.

=item B<-version>

Print B<autoinst>'s version number and exit.

=back


=head2 Font creation options

=over 4

=item B<-encoding>=I<encoding[,encoding]>

Generate the specified encoding(s) for the text fonts.
Multiple encodings may be specified as a comma-separated list
(without spaces!); the default choice of encodings is C<OT1,LY1,T1>.

For each encoding argument, B<autoinst> will first check if it is
the filename of an encoding file, and if found it will use that;
otherwise the argument is assumed to be the name of one of
the built-in encodings.
Currently B<autoinst> comes with built-in support for the OT1, T1/TS1, LY1, LGR,
T2A/B/C and T3/TS3 encodings.
(These files are called F<fontools_ot1.enc> etc. to avoid name clashes
with other packages; the F<fontools_> prefix may be omitted.)

=item B<-ts1>/B<-nots1>

Control the creation of TS1-encoded fonts. The default is B<-ts1>
if the text encodings (see I<-encoding> above) include T1,
B<-nots1> otherwise.

=item B<-lining>/B<-nolining>

Control the creation of fonts with lining figures. The default is
B<-lining>.

=item B<-oldstyle>/B<-nooldstyle>

Control the creation of fonts with oldstyle figures. The default is
B<-oldstyle>.

=item B<-proportional>/B<-noproportional>

Control the creation of fonts with proportional figures. The default is
B<-proportional>.

=item B<-tabular>/B<-notabular>

Control the creation of fonts with tabular figures. The default is
B<-tabular>.

=item B<-smallcaps>/B<-nosmallcaps>

Control the creation of small caps fonts. The default is
B<-smallcaps>.

=item B<-swash>/B<-noswash>

Control the creation of swash fonts. The default is B<-swash>.

=item B<-titling>/B<-notitling>

Control the creation of titling families. The default is B<-titling>.

=item B<-superiors>/B<-nosuperiors>

Control the creation of fonts with superior characters.
The default is B<-superiors>.

=item B<-inferiors> [ = B<none> | B<auto> | B<subs> | B<sinf> | B<dnom> ]

=item B<-noinferiors>

The OpenType standard defines several kinds of digits that might be used
as inferiors or subscripts: "Subscripts" (OpenType feature C<subs>),
"Scientific Inferiors" (C<sinf>), and "Denominators" (C<dnom>).
This option allows the user to determine which of these styles B<autoinst>
should use for the inferior characters.
Alternatively, the value "auto" tells B<autoinst> to use the first value
in C<sinf>, C<subs> or C<dnom> that is supported by the font.
Saying just B<-inferiors> is equivalent to B<-inferiors=auto>;
otherwise the default is B<-noinferiors>.

I<< If you specify a style of inferiors that isn't present in the font,
B<autoinst> will fall back to its default behaviour of not creating fonts
with inferiors at all; it won't try to substitute one of the other styles. >>

=item B<-fractions>/B<-nofractions>

Control the creation of fonts with numerators and denominators.
The default is B<-nofractions>.

=item B<-ligatures>/B<-noligatures>

Some fonts contain glyphs for the standard f-ligatures (ff, fi, fl, ffi, ffl),
but don't provide a C<liga> feature to access these.
This option tells B<autoinst> to add extra C<LIGKERN> rules to
the generated fonts to enable the use of these ligatures.
The default is B<-ligatures>, except for typewriter fonts.

Specify B<-noligatures> to disable generation of ligatures even for fonts
that do contain a C<liga> feature.

=item B<-ornaments>/B<-noornaments>

Control the creation of ornament fonts. The default is B<-ornaments>.

=item B<-serif>/B<-sanserif>/B<-typewriter>

Install the font as a serif, sanserif or typewriter font, respectively.
This changes how you access the font in LaTeX:
with C<\rmfamily>/C<\textrm>, C<\sffamily>/C<\textsf>
or C<\ttfamily>/C<\texttt>.

Installing the font as a typewriter font will cause two further changes:
it will - by default - turn off the use of f-ligatures
(though this can be overridden with the I<-ligatures> option),
and it will disable hyphenation for this font.
This latter effect cannot be re-enabled in B<autoinst>;
if you want typewriter text to be hyphenated, use the F<hyphenat> package.

If none of these options is specified, B<autoinst> tries to guess:
if the font's filename contains the string "mono"
or if the field C<isFixedPitch> in the font's C<post> table is True,
it will select B<-typewriter>;
else if the filename contains "sans" it will select B<-sanserif>;
otherwise it will opt for B<-serif>.

=item B<-math>

Tells B<autoinst> to create basic math fonts (see above).

=item B<-mathspacing>=I<amount>

Letterspace each character in the math fonts by I<amount> units,
where 1000 units equal one em.
In my opinion, many text fonts benefit from letterspacing by 50 to 100 units
when used in maths; some fonts need even more. Use your own judgement!

=back


=head2 Output options

=over 4

=item B<-t1suffix> [ = I<SUFFIX> ]

Tell B<autoinst> to modify the font names of all generated Type1-fonts,
by adding I<SUFFIX> to the family name.
If you use this option without specifying a I<SUFFIX> value,
B<autoinst> will use the value "PS".
The default behaviour when this option is not given
is to not modify font names at all.

See also L</OpenType fonts and licensing issues> in L<WARNINGS AND CAVEATS> above.

=item B<-target>=I<DIRECTORY>

Install all generated files into the TEXMF tree at I<DIRECTORY>.

By default, B<autoinst> searches the $TEXMFLOCAL and $TEXMFHOME trees
and installs all files into the first user-writable TEXMF tree it finds.
If B<autoinst> cannot find such a user-writable directory
(which shouldn't happen, since $TEXMFHOME is supposed to be user-writable)
it will print a warning message and put all files into the subdirectory
C<autoinst_output/> of the current directory.
It's then up to the user to move the generated files to a better location
and update all relevant databases
(usually by calling F<texhash> and F<updmap>).

=item B<-vendor>=I<VENDOR>

=item B<-typeface>=I<TYPEFACE>

These options are equivalent to F<otftotfm>'s I< --vendor> and I< --typeface>
options: they change the "vendor" and "typeface" parts of the names of the
subdirectories in the TEXMF tree where generated files will be stored.
The default values are "lcdftools" and the font's FontFamily name.
These options change I<only> directory names,
not the names of any generated files.

=item B<-logfile>=I<filename>

Write log data to F<filename> instead of the default F<< <fontfamily>.log >>.
If the file already exists, B<autoinst> appends to it;
it doesn't overwrite an existing file.

=back


=head2 Specialist options

=over 4

=item B<-defaultlining>/B<-defaultoldstyle>

=item B<-defaulttabular>/B<-defaultproportional>

Tell B<autoinst> which figure style is the current font family's default
(i.e., which figures you get when you don't specify any OpenType features).

I<Don't use these options unless you are certain you need them!>
They are only needed for fonts that don't provide OpenType features
for their default figure style; and even in that case,
B<autoinst>'s default values (B<-defaultlining> and B<-defaulttabular>)
are usually correct.

=item B<-nfssweight>=I<code>=I<weight>

=item B<-nfsswidth>=I<code>=I<width>

Map the NFSS code I<code> to the given weight or width,
overriding the built-in tables.
Each of these options may be given multiple times,
to override more than one NFSS code.
Example: to map the C<ul> code to the "Thin" weight,
use C<-nfssweight=ul=thin>.
To inhibit the use of the C<ul> code completely,
use C<-nfssweight=ul=>.

=item B<-extra>=I<extra options>

Pass I<extra options> to the commands for I<otftotfm>.
To prevent I<extra options> from accidentily being interpreted as
options to B<autoinst>, they should be properly quoted.

=item B<-nofigurekern>

Some fonts provide kerning pairs for tabular figures.
This is very probably not what you want
(e.g., numbers in tables won't line up exactly).
This option adds extra I< --ligkern> options
to the commands for I<otftotfm> to suppress such kerns.
Note that this option leads to very long commands (it adds
one hundred I< --ligkern> options), which may cause problems on some systems;
hence it is not active by default.

=back


=head1 SEE ALSO

Eddie Kohler's B<TypeTools> and B<T1Utils> (F<http://www.lcdf.org/type>).

B<Perl> can be obtained from F<http://www.perl.org>;
it is included in most Linux distributions.
For Windows, try ActivePerl (F<http://www.activestate.com>)
or Strawberry Perl (F<http://strawberryperl.com>).

B<LuaTeX> (F<http://www.luatex.org>) and
B<XeTeX> (F<http://www.tug.org/xetex>)
are Unicode-aware TeX engines that can use OpenType fonts directly,
without any (La)TeX-specific support files.

The B<FontPro> project (F<https://github.com/sebschub/FontPro>)
offers very complete LaTeX support (even for typesetting maths) for
Adobe's Minion Pro, Myriad Pro and Cronos Pro font families.


=head1 AUTHOR

Marc Penninga (F<marcpenninga@gmail.com>)

When sending a bug report, please give as much relevant information as
possible; this usually includes (but may not be limited to) the log file
(please add the I<-verbose> command-line option, for extra info).
If you see any error messages, please include these I<verbatim>;
don't paraphase.


=head1 COPYRIGHT

Copyright (C) 2005-2021 Marc Penninga.


=head1 LICENSE

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 2 of the License,
or (at your option) any later version.
A copy of the text of the GNU General Public License is included in
the I<fontools> distribution; see the file F<GPLv2.txt>.


=head1 DISCLAIMER

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.


=head1 VERSION

This document describes B<autoinst> version 20210401.


=head1 RECENT CHANGES

(See the source for the full story, all the way back to 2005.)

=over 12

=item I<2021-04-01>

The I<-encoding> option now also accepts filenames of encoding files
in directories other than the current directory.
Directory names containing spaces do (or at least should) also work.

=item I<2020-12-18>

Fixed a problem with files not being found on Windows.
Added extra C<--unicoding> options to prevent getting
lowercase f-ligatures in smallcaps for some buggy fonts.
Optimized font info parsing for DTL and TypeBy font families.
Cleaned up the code for better maintainability.

=item I<2020-07-29>

Some changes in the generated F<sty> and F<fd> files,
to improve compatibility with the F<microtype> package.
Made sure that F<pfb> fonts are always generated whenever
the input fonts are in F<otf> format.
Added the I<-t1suffix> command-line option,
to modify the font and file names of those generated Type1 fonts.

=item I<2020-06-19>

Added the C<nomathgreek> option to generated style files.
Reorganized the generated style files to make them more
standards-conforming.

=item I<2020-05-27>

Added basic (and still somewhat experimental) math support.
Implemented the C<scale=MatchLowercase> option value
in the generated style files.
"Wide" fonts are mapped to the C<sx> NFSS code instead of C<x>,
to cater for League Mono Variable's Wide and Extended widths.
The generated style files now use C<\textsup> and C<\textinf>
instead of the more cryptic C<\textsu> and C<\textin> to access
superior and inferior characters
(though the old forms are retained for backwards compatibility).

=item I<2020-05-11>

When present, use encoding files in the current working directory
in preference of the ones that come with B<autoinst>.
Changed the way ornament fonts are created; ornament glyphs are now
always included in the position chosen by the font's designer.

=item I<2020-04-28>

Fix a bug where the first font argument would be mistaken for
an argument to I<-inferiors>.

=item I<2020-01-29>

Don't create empty subdirectories in the target TEXMF tree.

=back


=begin Really_old_history

=over 12

=item I<2019-11-18>

Fine-tuned calling of F<kpsewhich> on Windows (patch by Akira Kakuto).
The font info parsing now also recognises numerical weights, e.g. in Museo.

=item I<2019-10-29>

The generated style files now use T1 as the default text encoding.

=item I<2019-10-27>

The mapping in F<fd> files between font series and standard NFSS attributes
now uses the new I<alias> function instead of I<ssub> (based on code by
Frank Mittelbach).
The way F<otftotfm> is called was changed to work around a Perl/Windows bug;
the old way might cause the process to hang.
Using the I<-target> option now implies I<-noupdmap>, since choosing
a non-standard target directory interferes with kpathsea/texhash and updmap.

=item I<2019-10-01>

Handle I<-target> directories with spaces in their path names.
Tweaked messages and logs to make them more useful to the user.

=item I<2019-07-12>

Replaced single quotes in calls to F<otfinfo> with double quotes,
as they caused problems on Windows 10.

=item I<2019-06-25>

=over 3

=item -

Added the I<-mergeweights> and I<-mergeshapes> options,
and improved I<-mergewidths>.

=item -

Improved the parsing of fonts' widths and weights.

=item -

Improved the mapping of widths and weights to NFSS codes.

=item -

Changed logging code so that that results of font info parsing
are always logged, even (especially!) when parsing fails.

=item -

Added a warning when installing fonts from multiple families.

=item -

Added simple recognition for sanserif and typewriter fonts.

=item -

Fixed error checking after calls to F<otfinfo>
(B<autoinst> previously only checked whether C<fork()> was successful,
not whether the actual call to F<otfinfo> worked).

=item -

Fixed a bug in the I<-inferiors> option;
when used without a (supposedly optional) value,
it would silently gobble the next option instead.

=back

=item I<2019-05-22>

Added the I<mainfont> option to the generated F<sty> files.
Prevented hyphenation for typewriter fonts
(added C<\hyphenchar\font=-1> to the C<\DeclareFontFamily> declarations).
Added the I<-version> option.

=item I<2019-05-17>

Changed the way the F<-ligatures> option works:
F<-ligatures> enables f-ligatures (even without a C<liga> feature),
F<-noligatures> now disables f-ligatures (overriding a C<liga> feature).

=item I<2019-05-11>

Separate small caps families are now also recognised when the family name
ends with "SC" (previously B<autoinst> only looked for "SmallCaps").

=item I<2019-04-22>

Fixed a bug in the generation of swash shapes.

=item I<2019-04-19>

Fixed a bug that affected -mergesmallcaps with multiple encodings.

=item I<2019-04-16>

Added the <-mergesmallcaps> option, to handle cases where
the small caps fonts are in separate font families.
Titling shape is now treated as a separate family instead of a distinct shape;
it is generated only for fonts with the C<titl> feature.
Only add f-ligatures to fonts when explicitly asked to (I<-ligatures>).

=item I<2019-04-11>

Tried to make the log file more relevant.
Added the I<-nfssweight> and I<-nfsswidth> options,
and finetuned the automatic mapping between fonts and NFSS codes.
Changed the name of the generated log file to F<< <fontfamily>.log >>,
and revived the I<-logfile> option to allow overriding this choice.
Made I<-mergewidths> the default (instead of I<-nomergewidths>).

=item I<2019-04-01>

Fine-tuned the decision where to put generated files;
in particular, create $TEXMFHOME if it doesn't already exist
and $TEXMFLOCAL isn't user-writable.

When we can't find a user-writable TEXMF tree,
put all generated files into a subdirectory C<./autoinst_output/>
instead of all over the current working directory.

Added "auto" value to the I<inferiors> option,
to tell B<autoinst> to use whatever inferior characters are available.

=item I<2019-03-14>

Overhauled the mapping of fonts (more specifically of weights and widths;
the mapping of shapes didn't change) to NFSS codes.
Instead of inventing our own codes to deal with every possible weight
and width out there, we now create "long" codes based on the names
in the font metadata.
Then we add C<ssub> rules to the F<fd> files to map the standard NFSS codes
to our fancy names (see the section B<NFSS codes>;
based on discussions with Frank Mittelbach and Bob Tennent).

=item I<2018-08-10>

Added encoding files for LGR and T2A/B/C to I<fontools>.

=item I<2018-03-26>

Added the I<-(no)mergewidths> option; tried to improve the documentation.

=item I<2018-03-26>

Added the "Text" weight and the I<-(no)mergewidths> option.
Changed the NFSS codes for "Thin" and "Book" to C<i> and C<o>, respectively.
Tried to improve the documentation.

=item I<2018-01-09>

Added the C<sl> weight for font families (such as Fira Sans) that contain both
"Book" and "Regular" weights (reported by Bob Tennent).
Added the "Two", "Four", "Eight" and "Hair" weights (for Fira Sans).

=item I<2017-06-16>

Changed the I<-inferiors> option from a binary yes-or-no choice to allow
the user to choose one of the C<subs>, C<sinf> and C<dnom> features.
B<autoinst> now always creates a log file.

=item I<2017-03-21>

Updated the F<fontools_ot1.enc> encoding file to include the "Lslash"
and "lslash" glyphs (thanks to Bob Tennent).

=item I<2015-11-22>

Bugfix: LaTeX doesn't like command names with dashes in it.

=item I<2015-05-13>

Fixed an error message that mixed up width and weight.

=item I<2014-04-04>

Fixed a bug in the font info parsing code.

=item I<2014-01-21>

"Oblique" or "slanted" fonts are now mapped to NFSS code C<sl> instead
of C<it>; added C<ssub> rules to the F<fd> files to substitute slanted fonts
for italic ones if the latter are missing. Fixed a few bugs.

=item I<2014-01-03>

Added the I<-dryrun> and I<-logfile> options; changed which info is logged.
Added the I<-lining>, I<-oldstyle>, I<-tabular> and I<-proportional>
options; the old options with those names have been renamed to
I<-defaultlining>, I<-defaultoldstyle> etc.

=item I<2013-10-31>

The previous change required Perl v5.14 or newer;
now it also works with older versions.

=item I<2013-10-01>

Added the I<-lining>, I<-oldstyle>, I<-tabular> and I<-proportional>
command line options.

=item I<2013-07-25>

The generated F<sty> files now use the I<mweights> package instead of
redefining C<\mddefault> and C<\bfdefault>.
Added C<scale> as an alias for the package option C<scaled>.

=item I<2013-02-06>

Bugfix: the directory names for map and encoding files contained
the "vendor" instead of the "typeface".

=item I<2013-01-03>

Added extra C<ssub> rules to the F<fd> files that substitute C<b> for C<bx>.
Verbose mode now also prints all generated commands before they're executed.

=item I<2012-10-25>

Added extra C<ssub> rules to the F<fd> files that substitute italic
shapes for slanted ones.

=item I<2012-09-25>

Added the I<-vendor>, I<-typeface> and I<-(no)updmap> command line options.

=item I<2012-07-06>

Documentation update.

=item I<2012-03-06>

Implemented the "splitting the font family into multiple subfamilies"
emergency strategy when font info parsing fails.
Added recognition for a number of unusual widths, weights and shapes.

=item I<2012-02-29>

Fixed a bug in the font parsing code,
where possible widths, weights and shapes where tested in the wrong order;
this led to "ExtraLight" fonts being recognised as "Light".
Added recognition for "Narrow" and "Wide" widths.
Also added the I<-(no)figurekern> command-line option.

=item I<2012-02-01>

Reorganised the code, and fixed some bugs in the process.
Added the I<-target> command-line option.
Made B<autoinst> install the F<fd> and F<sty> files in
the same TEXMF tree as the other generated files.
Generate OT1, T1 and LY1 encoded text fonts by default.
Made I<-titling> a default option (instead of I<-notitling>).
Updated the documentation.

=item I<2011-06-15>

Fixed the font info parsing code for some fonts that are
too lazy to spell out "Italic" in full.

=item I<2010-04-29>

The I< --feature=kern> option is only used for fonts that
contain either a I<kern> feature or a I<kern> table.
Font feature selection commands in the F<sty> file are only
generated for shapes and figure styles that are supported
by the current font, and whose generation has not been
turned off using the command-line options.
Fixed the font info parsing to work with the Condensed fonts
in the Minion Pro family.

=item I<2010-04-23>

Always provide the I< --feature=kern> option to F<otftotfm>,
even if the font doesn't have a I<kern> feature;
this will make F<otftotfm> use the I<kern> table if present.
For fonts without a I<liga> feature, add I< --ligkern>
options for the common f-ligatures to the F<otftotfm> command line,
so that any ligatures present in the font will still be used.
Bug fix: the generated F<sty> files now work for font families
with names containing digits.

=item I<2009-04-09>

Prefixed the filenames of  the included encoding files with
I<fontools_>, to prevent name clashes with other packages.

=item I<2009-04-06>

A small patch to the C<get_orn> subroutine:
it now also recognises the I<bullet.xxx> ornament glyphs
in Adobe Kepler Pro.

=item I<2007-08-07>

Fixed a small bug with filename quoting on Windows.

=item I<2007-07-31>

Changed the tables that map weights and widths to NFSS codes:
in some extended families, different combinations of
weight and width were mapped to the same series.
Added a work-around for incorrect size info in some Kepler fonts.
Fixed a small bug in the generated commands for otftotfm
(sometimes, the C<onum> feature was included twice).
Added encoding file for OT1 to the I<fontools> collection.

=item I<2007-07-27>

Two bugfixes: a closing brace was missing in the generated style file,
and the NFSS series was formed as "width plus weight" instead of the reverse.

=item I<2007-06-10>

Bugfix: silently replacing \DeclareOption, \ProcessOptions and
\ExecuteOptions with their counterparts from the xkeyval package
caused problems for some other packages.

=item I<2007-06-04>

Added the I< --no-updmap> option to all generated commands for F<otftotfm>
(except the last); this should yield a significant speed-up for large
families (suggested by Steven E. Harris).
Tweaked the font info parsing to work around a bug in the naming of
some FontFont fonts, where every font is in a family of its own.
Added the C<scaled> option (including the loading of F<xkeyval>)
to the generated style file.
Extended the output of the I<-verbose> option.

=item I<2007-02-08>

Yet Another Complete Rewrite.
The code is now much more readable and more flexible;
the program can now handle fonts from different families,
as well as multiple text encodings.
Rewrote the font info parsing code to work for Arno Pro.

=item I<2006-10-11>

The program determines the fonts' weights, widths and shapes by parsing
the output from C<otfinfo --info> instead of the font filename.
This should make B<autoinst> work for non-Adobe fonts.
Filenames with spaces now work as well.

=item I<2006-08-31>

Made the generated style files try to include F<fontaxes.sty>;
changed the names of the generated fonts and families
(to make the previous change possible);
added command-line options for most font styles and shapes;
tweaked the filename parsing code for Cronos Pro and Gill Sans Pro;
added runtime generation of encoding vectors for ornament fonts
(because GaramondPremier's ornament names differ from other fonts);
changed the NFSS-code for italic small caps and titling to C<scit> and C<tlit>
(to work with F<fontaxes>);
and edited (and hopefully improved) the documentation.

=item I<2005-10-03>

When creating LY1, T1, OT1 or TS1 encoded fonts, the I<-coding-scheme>
option is added to the commands for F<otftotfm>; this should make the
generated F<pl> and F<vpl> files acceptable to I<fontinst>.
Also elaborated the documentation somewhat and fixed a small bug.

=item I<2005-09-22>

Added check to see if filename parsing succeeded;
updated the filename parsing code to cater for GaramondPremier Pro,
Silentium Pro and some non-Adobe fonts;
added the I<-sanserif> and I<-typewriter> options and hacked the
style files to support using several different font families in one document.

=item I<2005-09-12>

Cleaned up the code (it now runs under the F<strict> and F<warnings> pragmas);
fixed a (rather obscure) bug that occurred when creating TS1-encoded
fonts for families with multiple optical masters and oldstyle digits;
added the I<medium, semibold> etc. options to the style file;
and improved the layout of the generated files.

=item I<2005-08-11>

The generated commands weren't actually executed, only printed...
Also added a small hack to cater for fonts
(such as some recent versions of MinionPro)
that contain swash characters but don't provide a C<swsh> feature.

=item I<2005-08-10>

Dropped the "fontname" scheme in favor of a more verbose naming scheme,
since many filenames were still more than eight characters long anyway.
Added F<nfssext.sty>-like commands to the generated style file.
Changed the default encoding to LY1 and added the "inferior" shape.

=item I<2005-08-01>

Rewrote (and hopefully improved) the user interface;
changed the program to by default execute the generated F<otftotfm> command
lines rather than writing them to a file;
added automatic determination of the "fontname" code for the font family;
changed the NFSS code for italic small caps to C<si>; added titling shapes;
changed the generated style
file to include an interface for the ornaments and to load Lehman's NFSS
extensions F<nfssext.sty> if this is installed; corrected the "fontname" codes
for OT1, T1, LY1 and user-specific encodings; extended the output generated by
the I<-verbose> option; and rewrote and extended the documentation.

=item I<2005-06-16>

Did some more finetuning to the filename-parsing code.

=item I<2005-05-31>

Generate correct fontname for OT1-encoded fonts.

=item I<2005-05-18>

Tried to make the filename-parsing code a bit more robust by adding several
weights and widths; changed the error that's displayed when filename parsing
fails; commented the code.

=item I<2005-04-29>

Rewrote large parts of the code (yes it I<was> even worse).

=item I<2005-04-18>

Changed default text-encoding to T1, added TS1.

=item I<2005-03-29>

Added support for font families with multiple widths.

=item I<2005-03-15>

First version.

=back

=end Really_old_history