summaryrefslogtreecommitdiff
path: root/Build/source/texk/afm2pl/afm2pl.c
blob: bcea467e6d5ed7177553c442e312040bbbcd6c8a (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
/* afm2pl
 * Copyright (C) 2002, 2005, 2009 Siep Kroonenberg
 * ntg-afm2pl@ntg.nl
 * based on afm2tfm.
 */

/* Here the opening comments from afm2tfm:
 *********************************************************************
 * (Modified by Don Knuth from Tom Rokicki's pre-VPL version.)
 *
 * VM/CMS port by J. Hafner (hafner@almaden.ibm.com), based on
 * the port by Alessio Guglielmi (guglielmi@ipisnsib.bitnet)
 * and Marco Prevedelli (prevedelli@ipisnsva.bitnet).
 * This port is still in test state.  No guarantees.
 * 11/3/92: more corrections to VM/CMS port. Now it looks correct
 * and will be supported by J. Hafner.
 *
 * More changes, primarily from Karl Berry, enough for a new version
 * number to 8.0; 1 December 1996.  Note that this version computes
 * checksums differently (more intelligently).
 *
 *********************************************************************/

/* Changed features:
 * writes pl with lig- and kern info instead of tfm
 * never adds characters not explicitly specified in the encoding
 * extra ligkern info, previously hardwired in the source, is now
 * read from an external file. This may include accented char ligatures.
 * Default behavior still matches afm2tfm, given the right ligkern
 * files.
 * letterspacing option, implemented as kerning pairs between any
 * two characters.
 *
 * For VM/CMS we no longer need asciified names for the font or the
 * encoding since we write an ascii pl file instead of a binary tfm.
 *
 * This version doesn't try as hard to always give sensible output.
 * On the other hand, since it uses simpler logic, it should be
 * easier for the user to figure out the cause of failures.
 *
 * changes in structure:
 * writes character metrics directly to an array
 * metric information is transformed in stages
 * does not create smallcaps
 */

/* differences between afm and tfm:
 * afm usually has a space char
 * afm lists chars by name and also includes unencoded chars
 * afm lists ligatures together with their first `component',
 *   and lists kerns separately.
 * afm implies 3-way ligs by recursive application of 2-way glyphs
 * afm allows negative heights and depths
 *
 * tfm usually doesn't have a space char
 * tfm may have boundarychar ligkerns instead of space ligkerns
 * tfm is lists chars by code and is glyphname-agnostic
 * tfm contains a ligkern table, where entries are sorted by left
 *   `component'. 3-way ligs are written out in one lig `program'.
 * tfm may contain some special-purpose ligs such as
 *   question quoteleft =: questiondown
 */

/*******************************************************************
 * includes, defines, system */

#ifdef HAVE_CONFIG_H
#define KPATHSEA 1
#include <kpathsea/config.h>
#include <kpathsea/debug.h>
#include <kpathsea/tex-file.h>
#include "c-auto.h"
#include <kpathsea/c-ctype.h>
#include <kpathsea/progname.h>
#include <kpathsea/version.h>
#else /* HAVE_CONFIG_H */
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <math.h>
#ifdef ATARIST
#include <float.h>
#endif
#endif /* HAVE_CONFIG_H */

#ifdef VMCMS
#define interesting lookstr     /* for 8 character truncation conflicts */
#include "dvipscms.h"
extern FILE *cmsfopen ();
extern char ascii2ebcdic[];
#ifdef fopen
#undef fopen
#endif
#define fopen cmsfopen
#endif

#ifdef WIN32
#define R_MODE  "rb"
#define W_MODE  "wb"
#else
#define R_MODE  "r"
#define W_MODE  "w"
#endif

/* from dvips.h: */

#ifdef VMS
#include "[.vms]vms.h"
#endif /* VMS */

/*
 *   Is your malloc big?
 */
#if defined(MSDOS) && !defined(__EMX__) && !defined(DJGPP)
#define SMALLMALLOC
#endif
#if defined(OS2) && defined(_MSC_VER)
#define SMALLMALLOC
#endif

#if (defined(MSDOS) && !defined(DJGPP)) || (defined(OS2) && defined(_MSC_VER)) || defined(ATARIST)
typedef long integer;
#else
typedef int integer;
#endif

#ifndef KPATHSEA
typedef char boolean;
#endif

#ifdef WIN32
#define Boolean boolean
#else
#ifndef __THINK__
typedef short Boolean ;
#endif
#endif

/**************************************************************
 * data structures */

/* Adobe char metrics; one lig- and kern linked list for each
 * adobechar
 */

struct lig {
  struct lig *next;
  const char *succ, *sub;
  short op, boundright;         /* boundright: succ is rboundarychar */
};

struct kern {
  struct kern *next;
  const char *succ;
  int delta;
};

/* metric info for one char */
struct adobeinfo {
  int adobenum, tfmnum, width;
  const char *adobename;
  int llx, lly, urx, ury;
  int nonstd_lk; /* non-standard ligs and/or kerns */
  struct lig *ligs;
  struct kern *kerns;
};
/* The nonstd_lk field is for efficiency in case of letterspacing.
 * With letterspacing, all glyphs originally without ligs or
 * kerns do show up in the ligkern table, but with identical
 * information. We write them in one go to the ligkern table.
 */

/* encodings */
struct encoding {
  const char *name;
  const char *vec[256];
};

/* struct to store the names of files with extra ligkern info */
struct nstrings {
  int n;
  const char **names;
};

/*************************************************************
 * global vars */

#define buflen 256
char buffer[buflen];            /* input buffer (modified while parsing) */
char obuffer[buflen];           /* unmodified copy of input buffer */
char *param;                    /* current position in input buffer */

const char *fontname = "Unknown";

struct encoding *afmencoding = NULL;
struct encoding *outencoding = NULL;
const char *ligoption = "1";          /* which extra ligkerns? */
const char *Ligoption = "1";          /* extra ligkern info after letterspacing */
int based_on;                   /* name output file based on name afm file? */
int no_prefix = 0;              /* don't look for afm2pl- prefixed filenames */
FILE *infile, *outfile;
const char *afmname, *outname;  /* names of input and output files */
const char *encfilename;        /* encoding file */
struct nstrings *ligfilenames;  /* for files with extra ligkern info */
struct nstrings *Ligfilenames;  /* same; for after letterspacing */
const char *ligfilename;

struct adobeinfo
**adobechars,                   /* array of adobeinfo structs, from afm and in afm order */
 *tfmptrs[256];                 /* same, but indexed by tfm order */

int tfmnext[256];               /* for characters encoded multiple times in output */

/* global font info */
int iglyph, nglyphs, nglyphsb;  /* glyph no., n. of glyphs in afm */
float italicangle = 0.0;
float newslant = 0.0; /* computed from slant and italicangle */
int fixedpitch;
int afm2tfm_compat = 0; /* create afm2tfm-compatible font dimensions */
int xheight = 0;
int fontspace = -1;
int fstretch = -1;
int fshrink = -1;
int fextra = -1;
int fquad = -1;
int charwidth = 0;

float efactor = 1.0, slant = 0.0;       /* requested transformation */
int lspace = 0;                 /* for letterspacing */
char *efactorparam, *slantparam, *lspaceparam;
int forceoctal = 0;
int keepligs = 0;               /* retain afm ligs in spite of lspace>0 */

int rboundarychar = -1;         /* the (right) boundary character */
const char *boundaryname = "||";      /* name of boundarychars for liginfo specs */
struct adobeinfo *rbound, *lbound;
char *boundglyph = NULL;
  /* glyph name of rboundarychar; non-null only if encoded */
  /* track presence of r- and l boundarychar ligkerns.
   * we don't check whether the real chars in those ligkerns
   * are encoded, so we may get false positives
   */

int missingchars = 0;
int verbose = 0;

/**************************************************************
 * general utility functions */

/* little hack: error message is warning unless it starts with '!' */
static void
error(const char *s)
{
  char *parasave;
  parasave = param;
  (void) fprintf (stderr, "%s\n", s);
  if (obuffer[0]) {
    (void) fprintf (stderr, "%s\n", obuffer);
    while (param > buffer) {
      (void) fprintf (stderr, " ");
      param--;
    }
    (void) fprintf (stderr, "^\n");
  }
  if (*s == '!')
    exit (1);
  param = parasave;
}

static char *
mymalloc(unsigned long len)
{
  register char *p;
  unsigned long i;

#ifdef SMALLMALLOC
  if (len > 65500L)
    error ("! can't allocate more than 64K!");
#endif
  p = malloc ((unsigned) len);
  if (p == NULL)
    error ("! out of memory");
  for (i = 0; i < len; i++)
    p[i] = 0;
  return (p);
}

static char *
newstring(const char *s)
{
  char *q = mymalloc ((unsigned long) (strlen (s) + 1));
  (void) strcpy (q, s);
  return q;
}

/* find a glyph name in an adobeinfo array */
static struct adobeinfo *
findname(struct adobeinfo **achars, int n, const char *p)
{
  register int i;
  for (i = 0; i < n; i++)
    if (achars[i] && strcmp (p, achars[i]->adobename) == 0)
      return achars[i];
  return NULL;
}

/* Find glyph info by name in the original adobechars array
 * We don't include the boundarychars in the search but always test
 * separately for those.
 */
static struct adobeinfo *
findadobe(const char *p)
{
  return findname (adobechars, nglyphs, p);
}

/* Find glyph info by name in target encoding */
static struct adobeinfo *
findtfm(const char *p)
{
  return findname (tfmptrs, 256, p);
}

/* just for adobechars, we sometimes want the index instead */
static int
findindex(const char *p)
{
  int i;
  for (i = 0; i < nglyphs; i++)
    if (adobechars[i] && strcmp (p, adobechars[i]->adobename) == 0)
      return i;
  return -1;
}

/* geometrically transformed boundingbox */
static int
transform(int x, int y)
{
  register double acc;
  acc = efactor * x + slant * y;
  return (int) (acc >= 0 ? floor (acc + 0.5) : ceil (acc - 0.5));
}

/* read a line from infile into buffer and obuffer */
static int
texlive_getline(void)
{
  register char *p;
  register int c;
  int maxline;

  param = buffer;
  p = buffer;
  maxline = buflen;
  c = 0; /* to suppress phony compiler warning */
  while (((c = getc (infile)) != EOF) && (c != '\n') && (c != '\r'))
    /* added: test for \r. The way we do it, the DOS cr/lf convention
     * leads to alternating empty lines, but that is ok.
     */
    if (--maxline > 0) *p++ = c;
  *p = 0;
  (void) strcpy (obuffer, buffer);
  if (p == buffer && c == EOF)
    return (0);
  else
    return (1);
}

/*******************************************************
 * file handling
 */

#ifndef KPATHSEA
/* simple versions of concat (concatenate with allocation),
 * kpse_find_suffix, xbasename and an enum for kpse_file_format_type.
 * This is to reduce the number of #ifdef KPATHSEA sections.
 */
typedef enum {
  kpse_afm_format, kpse_lig_format, kpse_enc_format
} kpse_file_format_type;

/* string concatenation with allocation */
static char *
concat(const char *s1, const char *s2)
{
  char *answer = (char *) malloc (strlen (s1) + strlen (s2) + 1);
  strcpy (answer, s1);
  strcat (answer, s2);

  return answer;
}

/* Return pointer to first character after `.' in last directory element
 * of NAME.  If the name is `foo' or `/foo.bar/baz', we have no extension.
 */
static const char *
find_suffix(const char *name)
{
  const char *slash_pos;
  const char *dot_pos = (char *) strrchr (name, '.');

  if (dot_pos == NULL)
    return NULL;

  /* find last directory separator */
  for (slash_pos = name + strlen (name);
       slash_pos > dot_pos &&
       (*slash_pos != ':' && *slash_pos != '\\' && *slash_pos != '/');
       slash_pos--);

  /* accept suffix only if after last path separator */
  return slash_pos > dot_pos ? NULL : dot_pos + 1;
}

/* Return pointer to filename with leading path stripped */
static const char *
xbasename(const char *name)
{
  const char *base = NULL;
  unsigned len = strlen (name);

  for (len = strlen (name); len > 0; len--) {
    if (name[len - 1] == ':' || name[len - 1] == '\\'
        || name[len - 1] == '/') {
      base = name + len;
      break;
    }
  }
  if (!base)
    base = name;
  return base;
}

#define ISALNUM(c) (isascii (c) && isalnum(c))

#endif
/* end of KPATHSEA replacements */

/* file open functions; abort in case of failure; return filename */

/* open file for reading
 * parameters: (pointer to) requested filename
 * return (pointer to) actual filename without dir
 * Since we only have one input file open at any time
 * we use a global file variable infile.
 * Note. The kpse lib fu concat itself takes care of
 * allocating the result string
 * kpse handling isn't so helpful in the enc- and lig cases,
 * so we add a suffix explicitly.
 */
static const char *
openin(const char *fname, kpse_file_format_type format, const char *ext)
{
#ifdef KPATHSEA
  char *realfname;

  realfname = NULL;
  if (!no_prefix && (!strcmp(ext, ".enc") || !strcmp(ext, ".lig"))) {
    realfname = kpse_find_file (concat("afm2pl-", fname), format, false);
    if (!realfname) {
      realfname = concat (concat("afm2pl-", fname), ext);
      realfname = kpse_find_file (realfname, format, false);
    }
  }
  if (!realfname) {
    realfname = kpse_find_file (fname, format, false);
    if (!realfname) {
      realfname = concat (fname, ext);
      realfname = kpse_find_file (realfname, format, false);
    }
  }
  if (!realfname)
    FATAL1 ("%s not found", fname);
  infile = kpse_open_file (realfname, format);
  if (infile)
    return xbasename (realfname);
  else
    FATAL1 ("couldn't open %s", realfname);
#else
  const char *realfname;

  realfname = fname;
  infile = fopen (realfname, R_MODE);
  if (!infile && !find_suffix (realfname)) {
    realfname = concat (fname, ext);
    infile = fopen (realfname, R_MODE);
  }
  if (infile)
    return realfname;
  else
    error (concat ("!couldn't open ", realfname));
#endif
  return NULL;
}

/* open file for writing
 * Parameter based_on: if non-zero, then fname was the name
 * of the afm file, and we have to construct a new name
 * based on fname:
 * - replace an extension ".afm" with ".pl"
 * - strip leading path+
 * In this function, kpathsea functions don't provide better
 * functionality, but they do improve portability.
 */
static const char *
openout(const char *fname, int based_on, const char *outext)
{
  const char *inext = ".afm";
  /* use inext+1 and outext+1 when the leading dot is not desired */
  const char *realfname;
  const char *suf;

  if (based_on) {  /* compute output filename */
    suf = find_suffix (fname);
    if (suf && !strcmp ((inext + 1), suf)) {    /* replace afm suffix */
      char * q;
      q = newstring (fname);
      q[suf - fname] = 0;
      strcat (q, (outext + 1));
      realfname = q;
      /* no allocation required: new suffix not longer than old one */
    } else         /* append new suffix */
      realfname = concat (fname, outext);
    realfname = xbasename (realfname);
  } else {
    suf = find_suffix (fname);
    if (suf)
      realfname = fname;
    else
      realfname = concat (fname, outext);
  }
  outfile = fopen (realfname, W_MODE);
  /* afm2tfm uses WRITEBIN instead of "w" for some OS-es */
  if (outfile)
    return realfname;
  else
    error (concat ("!", concat (realfname, " not found")));
  return NULL;
}

/********************************************************
 * reading the afm
 */

const char *interesting[] = { "FontName", "ItalicAngle", "IsFixedPitch",
  "XHeight", "C", "KPX", "EncodingScheme",
  "StartCharMetrics", "CharWidth", NULL
};
#define FontName (0)
#define ItalicAngle (1)
#define IsFixedPitch (2)
#define XHeight (3)
#define C (4)
#define KPX (5)
#define EncodingScheme (6)
#define StartCharMetrics (7)
#define CharWidth (8)
#define NONE (-1)
static int
interest(char *s)
{
  register const char **p;
  register int n;

  for (p = interesting, n = 0; *p; p++, n++)
    if (strcmp (s, *p) == 0)
      return (n);
  return (NONE);
}

/* At function call, param points to the first char of the next
 * string, or to eol.
 * In the input buffer, a terminating space is replaced with a null char.
 * Before termination, param is moved to the start of the next
 * string, or to eol.
 */

/* next (parameter) string (param is input pointer),
 * with allocation */

static char *
paramnewstring(void)
{
  register char *p, *q;

  p = param;
  while (*p > ' ')
    p++;
  if (*p != 0)
    *p++ = 0;
  q = newstring (param);
  while (*p && *p <= ' ')
    p++;
  param = p;
  return (q);
}

/* next (parameter) string from afm file (param is input pointer),
 * pre-allocated */

static char *
paramstring(void)
{
  register char *p, *q;

  p = param;
  while (*p > ' ')
    p++;
  q = param;
  if (*p != 0)
    *p++ = 0;
  while (*p && *p <= ' ')
    p++;
  param = p;
  return (q);
}

static int
paramnum(void)
{
  register char *p;
  int i;

  p = paramstring ();
  if (sscanf (p, "%d", &i) != 1)
    error ("! integer expected");
  return (i);
}

static float
paramfloat(void)
{
  register char *p;
  float i;

  p = paramstring ();
  if (sscanf (p, "%f", &i) != 1)
    error ("! number expected");
  return (i);
}

static void
expect(const char *s)
{
  if (strcmp (paramstring (), s) != 0) {
    (void) fprintf (stderr, "%s expected: ", s);
    error ("! syntax error");
  }
}

/* allocating and initializing structs */

/* initialize afm info for one char */
static struct adobeinfo *
newchar(void)
{
  register struct adobeinfo *ai;

  ai = (struct adobeinfo *) mymalloc ((unsigned long)
                                      sizeof (struct adobeinfo));
  ai->adobenum = -1;
  ai->tfmnum = -1;
  /* ai->kern_as = NULL; */
  ai->width = -1;
  ai->adobename = NULL;
  ai->llx = -1;
  ai->lly = -1;
  ai->urx = -1;
  ai->ury = -1;
  ai->ligs = NULL;
  ai->kerns = NULL;
  /* ai->kern_equivs = NULL ; */
  return (ai);
}

static struct kern *
newkern(void)
{
  register struct kern *nk;

  nk = (struct kern *) mymalloc ((unsigned long) sizeof (struct kern));
  nk->next = NULL;
  nk->succ = NULL;
  nk->delta = 0;
  return (nk);
}

static struct lig *
newlig(void)
{
  register struct lig *nl;

  nl = (struct lig *) mymalloc ((unsigned long) sizeof (struct lig));
  nl->next = NULL;
  nl->succ = NULL;
  nl->sub = NULL;
  nl->op = 0;      /* the default =: op */
  nl->boundright = 0;
  return (nl);
}

/* read and interpret afm info for 1 char
 * adobeptrs is an array of pointers to adobeinfo structs
 * indexed by adobenum.
 * */
static void
handlechar(void)
{                  /* an input line beginning with C */
  register struct adobeinfo *ai;
  register struct lig *nl;

  if ((++iglyph) >= nglyphs)
    error ("!Too many glyphs in afm");
  adobechars[iglyph] = newchar ();
  ai = adobechars[iglyph];
  ai->adobenum = paramnum ();
  expect (";");
  expect ("WX");
  ai->width = paramnum ();
  if (fixedpitch)
    charwidth = ai->width;
  expect (";");
  expect ("N");
  ai->adobename = paramnewstring ();
  if ((ai->adobenum) >= 0)
    afmencoding->vec[ai->adobenum] = newstring (ai->adobename);
  expect (";");
  expect ("B");
  ai->llx = paramnum ();
  ai->lly = paramnum ();
  ai->urx = paramnum ();
  ai->ury = paramnum ();
  expect (";");
/* Now look for ligatures (which aren't present in fixedpitch fonts) */
  while (*param == 'L' && !fixedpitch) {
    expect ("L");
    nl = newlig ();
    nl->succ = paramnewstring ();
    nl->sub = paramnewstring ();
    nl->next = ai->ligs;
    ai->ligs = nl;
    expect (";");
  }
}

static void
handlekern(void)
{                  /* an input line beginning with KPX */
  register struct adobeinfo *ai;
  register char *p, *sc;
  register struct kern *nk;
  int dlt;

  p = paramstring ();
  ai = findadobe (p);
  if (!ai)
    error ("kern char not found");
  else {
    sc = paramstring ();
    dlt = paramnum ();
    if (dlt) {
      nk = newkern ();
      nk->succ = newstring (sc);
      nk->delta = dlt;
      nk->next = ai->kerns;
      ai->kerns = nk;
    }
  }
}

/* read afm file */
static void
readadobe(void)
{
  const char *inname;
  int i;

  /* open afm file */
  inname = newstring (afmname);
  inname = openin (inname, kpse_afm_format, ".afm");

  nglyphs = -1;    /* allocate adobechars at StartCharMetrics */
  afmencoding = (struct encoding *) mymalloc ((unsigned long)
                                              sizeof (struct encoding));
  for (i = 0; i < 256; i++)
    afmencoding->vec[i] = ".notdef";
  afmencoding->name = "Unspecified";

  while (texlive_getline ()) {
    switch (interest (paramstring ())) {
    case FontName:
      fontname = paramnewstring ();
      break;
    case EncodingScheme:
      afmencoding->name = paramnewstring ();
      break;
    case ItalicAngle:
      italicangle = paramfloat ();
      break;
    case IsFixedPitch:
      if (*param == 't' || *param == 'T')
        fixedpitch = 1;
      else
        fixedpitch = 0;
      break;
    case XHeight:
      xheight = paramnum ();
      break;
    case StartCharMetrics:
      nglyphs = paramnum ();
      nglyphsb = nglyphs + 1;
      iglyph = -1;
      /* Allocate adobechars array (just the array of pointers).
       * Reserve extra slot for rboundarychar
       */
      adobechars =
        (struct adobeinfo **) mymalloc ((unsigned long) (nglyphs+1) *
                                        (unsigned long) sizeof (struct
                                                                adobeinfo
                                                                *));
      break;
    case C:
      handlechar ();
      break;
    case KPX:
      handlekern ();
      break;
    case CharWidth:
      charwidth = paramnum ();
      fixedpitch = 1;
      break;
    default:
      break;
    }
  }
  fclose (infile);
  infile = NULL;
}

/* now some changes to the afm info */
static void
changeadobe(void)
{
  struct adobeinfo *ai;
  int i;
  /* float newslant; local declaration masks global one */

  /* A fix: avoiding negative heights or depths.
   * They break accents in math mode, among other things.
   */
  for (i = 0; i < nglyphs; i++) {
    ai = adobechars[i];
    if (ai->lly > 0)
      ai->lly = 0;
    if (ai->ury < 0)
      ai->ury = 0;
  }

  /* apply any requested geometric transforms */
  if (efactor != 1.0 || slant != 0.0) {
    for (i = 0; i < nglyphs; i++) {
      ai = adobechars[i];
      ai->width = transform (ai->width, 0);
      ai->llx = transform (ai->llx, ai->lly);
      ai->urx = transform (ai->urx, ai->ury);
    }
  }
  newslant = (double) slant -
    efactor * tan (italicangle * (3.1415926535 / 180.0));

  /* Avoid output of '(SLANT R -0.000000)' due to floating point
   * rounding; neither round() nor fabs() need be defined.  */
  if ((newslant < 0.0) && (newslant*2000000.0 >= -1.0))
    newslant = 0.0;
   
  /* if !keepligs, remove native ligatures */
  if (!keepligs && lspace>0) {
    for (i = 0; i < nglyphs; i++)
      adobechars[i]->ligs = NULL;
  }

  /* create a left and right boundarychar entries - just in case,
   * but don't add them (yet) to adobechars */
  for (i = 0; i < 2; i++) {
    ai = newchar ();
    ai->adobenum = -1;
    ai->width = 0;
    ai->llx = 0;
    ai->lly = 0;
    ai->urx = 0;
    ai->ury = 0;
    ai->adobename = boundaryname;
    if (i == 0)
      lbound = ai;
    else
      rbound = ai;
  }

  /* global font dimensions */

  /* The following may depend on the -f parameter */

  if (xheight == 0) {
    ai = findadobe ("x");
    if (ai)
      xheight = ai->ury;
    else
      xheight = 400;
  }

  if (afm2tfm_compat) { /* -f 'afm2tfm'*/

    ai = findadobe ("space");
    if (ai)
      fontspace = ai->width; /* transform already applied */
    else {
      if (fixedpitch)
        fontspace = charwidth;
      else
        transform(500, 0);
    }
    fstretch = (fixedpitch) ? 0 : transform (300, 0);
    fshrink = (fixedpitch) ? 0 : transform (100, 0);
    /* fextra = transform (111, 0); */
    fquad = transform (1000, 0);

  } else if (!fixedpitch) {

    /* some may be set by a numerical -f parameter) */

    if (fontspace<0) {
      ai = findadobe ("space");
      if (ai)
        fontspace = ai->width; /* transform already applied */
      else {
        fontspace = transform(500, 0);
      }
    }
    if (fquad<0) {
      ai = findadobe ("zero");
      if (ai) fquad = 2 * ai->width;
      else if (fixedpitch) fquad = 2 * charwidth;
      else fquad = transform (1000, 0);
    }
    if (fstretch<0) fstretch = fontspace / 2;
    if (fshrink<0) fshrink = fontspace / 3;
    if (fextra<0) fextra = fontspace / 3;
  } else { /* fixedpitch && !afm2tfm_compat */
    if (fontspace<0) fontspace = charwidth;
    if (fstretch<0) fstretch = 0;
    if (fshrink<0) fshrink = 0;
    if (fquad<0) fquad = 2 * charwidth;
    if (fextra<0) fextra = charwidth;
  }
}

/**************************************************
 * reading encodings
 */

char smbuffer[100];             /* for tokens */

/*   Here we get a token from the encoding file.  We parse just as
 *   much PostScript as we expect to find in an encoding file.  We
 *   allow commented lines and names like 0, .notdef, _foo_.  We do
 *   not allow //abc.
 */
static char *
gettoken(void)
{
  char *p, *q;

  while (1) {
    while (param == 0 || *param == 0) {
      if (texlive_getline () == 0)
        error ("! premature end in encoding file");
    }
    if (param[0] == '%') {
      param[0] = 0;     /* be done with this line */
      continue;
    }
    while (*param && *param <= ' ')
      param++;
    if (*param) {
      if (*param == '[' || *param == ']' ||
          *param == '{' || *param == '}') {
        smbuffer[0] = *param++;
        smbuffer[1] = 0;
        return smbuffer;
      } else if (*param == '/' || *param == '-' || *param == '_' ||
                 *param == '.' ||
                 ('0' <= *param && *param <= '9') ||
                 ('a' <= *param && *param <= 'z') ||
                 ('A' <= *param && *param <= 'Z')) {
        smbuffer[0] = *param;
        for (p = param + 1, q = smbuffer + 1;
             *p == '-' || *p == '_' || *p == '.' ||
             ('0' <= *p && *p <= '9') ||
             ('a' <= *p && *p <= 'z') ||
             ('A' <= *p && *p <= 'Z'); p++, q++)
          *q = *p;
        *q = 0;
        param = p;
        return smbuffer;
      }
    }
  }
}

/* This routine reads the encoding file.
 * Return value: pointer to encoding.
 *
 * There is just one reason why we read the encoding vector
 * before the extra ligkern information: if a (r)boundarychar is
 * specified by number then we want to translate it into
 * a glyph name.
 *
 * We also create tfmptrs as a reencoded version of adobechars, and
 * tfmnext, which tracks multiple encodings of a single glyph and is
 * best explained by the code creating it.
 */
static void
readencoding(void)
{
  char *p;
  int i, inx;
  struct adobeinfo *ai;

  if (infile)
    error ("! oops; internal infile error");
  if (encfilename) {
    encfilename =
      openin (encfilename, kpse_enc_format, ".enc");
    param = 0;
    if (infile == 0)
      error ("! couldn't open that encoding file");
    outencoding = (struct encoding *) mymalloc
      ((unsigned long) sizeof (struct encoding));
    for (i = 0; i < 256; i++)
      outencoding->vec[i] = ".notdef";
    outencoding->name = "Unspecified";
    p = gettoken ();
    if (*p != '/' || p[1] == 0)
      error ("! first token in encoding must be literal encoding name");
    outencoding->name = newstring (p + 1);
    p = gettoken ();
    if (strcmp (p, "["))
      error ("! second token in encoding must be mark ([) token");
    for (i = 0; i < 256; i++) {
      p = gettoken ();
      if (*p != '/' || p[1] == 0)
        error ("! tokens 3 to 257 in encoding must be literal names");
      outencoding->vec[i] = newstring (p + 1);
    }
    p = gettoken ();
    if (strcmp (p, "]"))
      error ("! token 258 in encoding must be make-array (])");
    fclose (infile);
    infile = 0;
  } else
    outencoding = afmencoding;

  /* find adobeinfo for each encoded glyph name
   * track multiple encodings (tfmnext).
   * For missing glyphs, this is not necessary.
   */
  for (i = 0; i < 256; i++)
    tfmnext[i] = -1;
  for (i = 0; i < 256; i++) {
    if (strcmp (outencoding->vec[i], ".notdef")) {
      ai = findadobe (outencoding->vec[i]);
      tfmptrs[i] = ai;
      if (ai) {
        inx = ai->tfmnum;
        if (inx == -1)
          ai->tfmnum = i;
        else {
          while (tfmnext[inx] != -1)
            inx = tfmnext[inx];
          tfmnext[inx] = i;
        }
      } else { /* missing glyph */
        if (!missingchars && verbose)
          fputs ("Missing glyphs\n", stderr);
        missingchars += 1;
        if (verbose) printf ("%s\n", outencoding->vec[i]);
      }
    } else /* empty slot */
      tfmptrs[i] = NULL;
  }
}

/****************************************************************
 * Processing extra ligkern info
 *
 * When these functions are called, we have available the afm data
 * and the raw encoding vector.
 * changeadobe has created adobeinfos for left and right boundarychar.
 * We use the encoding vector ONLY to translate an rboundarychar spec
 * into an rboundarychar name. However, normally an rboundarychar will
 * occupy an otherwise unused slot in the encoding, in which case
 * the name is irrelevant.
 * I don't see the point of a numeric rboundarychar specification:
 * either one wants to use a specific character or the numeric value
 * doesn't matter. But I allow it for backward compatibility.
 *
 * extra ligkern info can come from:
 * - comments in the encoding file
 * - lig files. These replace the hard-coded set in afm2tfm.
 * afm2tfm applies its own set only if the enc file contains no
 * ligkern instructions. This is also the default behavior of
 * afm2pl.
 *
 * Typically, extra ligkern info may contain:
 * - tex-specific hacks such as `less less =: guillemotleft'
 * - deletion of space- and number kerns
 * - kern accented chars as their unaccented versions
 * - the f/l/i ligatures, in case they were absent from the afm.
 *
 * note. afm2pl allows first copying space kerns
 * to boundarychar kerns and then deleting the space kerns, leaving
 * the boundarychar kerns intact.
 *
 * There was a function for creating accented char ligatures.
 * This doesn't prevent TeX from compositing accented chars
 * so it is not very useful.
 * In afm2tfm this function was never called and I removed it.
 * I created a file accents.lig which may be loaded for these
 * accent ligs but default isn't.
 */

/* Notation of ligkern specs:
 * char1 char2 =: char3    => replace char1 char2 with char3
 *   and more generally:
 * char1 char2 ligop char3 => char1 char2 ligop char3
 * char1 {} char2          => delete char1 char2 kern
 * char1 <> char2          => kern char1 the same as char2
 * || = char               => char is right boundary char
 *
 * Notes.
 * - cork.enc contains specs `char @{@} char' instead of `char {} char'
 * - The ligkern specs use `||' for both lboundarychar and
 *   rboundarychar. The context must make clear which one is intended.
 *   I store them in separate adobechar structs.
 */

/* These are the eight ligature ops, in pl terms and in METAFONT terms.
 */
const char *plligops[] = {
  "LIG", "/LIG", "/LIG>", "LIG/", "LIG/>", "/LIG/", "/LIG/>",
  "/LIG/>>", 0
};
const char *encligops[] = {
  "=:", "|=:", "|=:>", "=:|", "=:|>", "|=:|", "|=:|>", "|=:|>>", 0
};

/* Make the kerning for character s1 equivalent to that for s2
 * but don't replace existing kerns.
 * It doesn't matter whether or not s2 is encoded.
 * In the pl file, the kerning info of both s1 and s2 will be written
 * out in full.
 */
static void
copykerns(char *s1, char *s2)
{
  int i, found, delta2, found1, found2;
  struct adobeinfo *ai, *ai1, *ai2;
  struct kern *nk, *nk1, *nk2;

  if (!strcmp (s1, s2))
    return;

  /* kerns with s1 and s2 on the left */
  if (!strcmp (boundaryname, s1))
    ai1 = lbound;
  else
    ai1 = findadobe (s1);
  if (!strcmp (boundaryname, s2))
    ai2 = lbound;
  else
    ai2 = findadobe (s2);
  if (ai1 && ai2 && ai2->kerns) {
    nk2 = ai2->kerns;
    while (nk2) {
      found = 0;
      nk1 = ai1->kerns;
      while (nk1) {
        if (!strcmp (nk1->succ, nk2->succ)) {
          found = 1;
          break;
        }
        nk1 = nk1->next;
      }
      if (!found) {
        nk1 = newkern ();
        nk1->succ = nk2->succ;
        nk1->delta = nk2->delta;
        nk1->next = ai1->kerns;
        ai1->kerns = nk1;
      }
      nk2 = nk2->next;
    }
  }

  /* kerns with s1 and s2 on the right. */
  if (!strcmp (boundaryname, s1) && boundglyph)
    s1 = boundglyph;
  if (!strcmp (boundaryname, s2) && boundglyph)
    s2 = boundglyph;
  /* a name '||' for s1/s2 is untouched */
  if (!strcmp (s1, s2))
    return;
  delta2 = 0; /* silence 'might be used uninitialized' warning */
  for (i = 0; i < nglyphs; i++) {
    ai = adobechars[i];
    found1 = 0;
    found2 = 0;
    nk = ai->kerns;
    while (nk) {
      if (!strcmp (nk->succ, s2)) {
        found2 = 1;
        delta2 = nk->delta;
      }
      if (!strcmp (nk->succ, s1))
        found1 = 1;
      nk = nk->next;
    }
    if (found2 && !found1) {
      nk1 = newkern ();
      nk1->next = ai->kerns;
      ai->kerns = nk1;
      nk1->succ = newstring (s1);
      /* can't copy s1, which is just a stack variable */
      nk1->delta = delta2;
    }
  }
}

/* remove kern between ai->adobechar and s2, where s2 != "*"
 */
static void
adobermkern(struct adobeinfo *ai, char *s2)
{
  struct kern *k, *kprev;
  char *s2a;
  int first;
  if (!ai->kerns)
    return;
  k = ai->kerns;
  if (!strcmp (s2, boundaryname) && boundglyph)
    s2a = boundglyph;
  else
    s2a = s2;
  kprev = k; /* silence 'might be used uninitialized' warning */
  first = 1;
  while (k) {
    if (!strcmp (s2a, k->succ) || !strcmp (s2, k->succ)) {
      if (first)
        ai->kerns = k->next;
      else
        kprev->next = k->next;
      return;
    }
    first = 0;
    kprev = k;
    k = k->next;
  }
}

/* remove kerns between s1 and s2 (wildcards allowed) */
static void
rmkern(char *s1, char *s2)
{
  int i;
  struct adobeinfo *ai;

  if (!strcmp (s1, "*")) {
    for (i = 0; i < nglyphs; i++) {
      ai = adobechars[i];
      adobermkern (ai, s2);
    }
    adobermkern (lbound, s2);
  } else if (!strcmp (s2, "*")) {
    if (!strcmp (s1, boundaryname))
      ai = lbound;
    else
      ai = findadobe (s1);
    if (ai)
      ai->kerns = NULL;
  } else {         /* remove single pair */
    if (!strcmp (s1, boundaryname))
      ai = lbound;
    else
      ai = findadobe (s1);
    if (!ai)
      return;
    adobermkern (ai, s2);
  }
}

/* With default ligkern option, need to know whether
 * the enc file contains ligkern specs
 */
int sawligkern;

/* zero-th iteration: look out for rboundarychar spec.
 * first iteration: look out for everything else.
 */
int lig_it;

/* set_rboundarychar is to be called after the ligkern specs have been
 * scanned for a rboundarychar spec but before we know whether it
 * will actually be used.
 */
static void
set_rboundarychar(int bch)
{
  int i;
  if (bch == -1) {
    /* find empty slot; skip 0, just to be safe */
    for (i = 1; i < 256; i++)
      if (!strcmp (outencoding->vec[i], ".notdef")) {
        rboundarychar = i;
        tfmptrs[i] = rbound;
        rbound->tfmnum = i;
        adobechars[nglyphs] = rbound;
        return;
      }
    error ("No tfm slot available for boundarychar");
  } else {
    rboundarychar = bch;
    if (tfmptrs[rboundarychar]) {
      rbound = tfmptrs[rboundarychar];
      boundglyph = newstring (rbound->adobename);
      nglyphsb = nglyphs; /* no extra slot in adobechars needed */
    } else {
      tfmptrs[bch] = rbound;
      rbound->tfmnum = bch;
      adobechars[nglyphs] = rbound;
    }
    return;
  }
}

/* Reads a ligkern line, which may contain several ligkern specs.
 * lig_it = 0: only process rboundarychar spec
 * lig_it != 0: process all other ligkern specs
 * lig_it = 2: post-letterspacing; only `{}' specs are allowed.
 */
static void
checkligkern(char *s, int isencfile)
{
  char *mlist[5];               /* tokens constituting a ligkern spec */
  int n, i, bch;
  struct adobeinfo *ai;

  if (s[0] == '%')
    s++;           /* skip optional leading `%' */
  /* Note. '%' is necessary for ligkern comments in an encoding file
   * and optional otherwise.
   */
  while (*s && *s <= ' ')
    s++;           /* skip to first token */
  if (!s[0])
    return;        /* empty line; done */
  if (isencfile && strncmp (s, "LIGKERN", 7)) /* not a ligkern line */
    return;
  if (!strncmp (s, "LIGKERN", 7))
    s += 7;        /* skip beyond `LIGKERN' */
  sawligkern = 1;
  while (*s && *s <= ' ')
    s++;
  param = s;
  while (*param) {
    /* collect next ligkern spec */
    for (n = 0; n < 5;) {
      /* collect next token for ligkern spec */
      if (*param == 0)
        break;     /* ligkern spec complete */
      mlist[n] = paramstring ();
      if (strcmp (mlist[n], ";") == 0)
        break;     /* ligkern spec complete */
      n++;
    }

    /* handle ligkern spec */
    if (n > 4)
      error ("! too many parameters in lig kern data");
    if (n < 3)
      error ("! not enough parameters in lig kern data");
    if (n == 3 && strcmp (mlist[1], "{}") == 0) {
      if (!lig_it)
        continue;
      if (lig_it == 2 && strcmp (mlist[0], "*") != 0) {
        ai = findadobe (mlist[0]);
        if (ai) ai->nonstd_lk = 1;
      }
      rmkern (mlist[0], mlist[2]);
    } else if (n == 3 && strcmp (mlist[1], "<>") == 0) {
      if (!lig_it)
        continue;
      if (lig_it == 2)
        error ("!Post-letterspacing <> kern spec not allowed");
      copykerns (mlist[0], mlist[2]);
    } else if (n == 3 && strcmp (mlist[0], boundaryname) == 0 &&
               strcmp (mlist[1], "=") == 0) {
      /* setting of rboundarychar; only during 0-th iteration */
      if (lig_it)
        continue;
      if (lig_it == 2)
        error ("!Post-letterspacing boundarychar spec not allowed");
      if (rboundarychar != -1)
        error ("! multiple boundary character commands?");
      if (sscanf (mlist[2], "%d", &bch) == 1) {
        /* number for rboundarychar */
        if (bch < 0 || bch > 255)
          error ("! boundary character number must be 0..255");
        else
          set_rboundarychar (bch);
      } else {     /* named rboundarychar */
        for (bch = 0; bch < 256; bch++)
          if (!strcmp (outencoding->vec[bch], mlist[2]))
            break;
        if (bch<256) boundglyph = newstring(mlist[2]);
        else {
          if (strcmp ("cwm", mlist[2])) error
           ("unencoded boundarychar; will use empty slot instead");
          bch = -1;
          boundglyph = newstring(boundaryname);
        }
        set_rboundarychar (bch);
      }
    } else if (n == 4) {        /* ligature: char succ lig_op result */
      int op = -1;

      if (!lig_it)
        continue;
      if (lig_it == 2)
        error ("!Post-letterspacing lig spec not allowed");
      for (i = 0; encligops[i]; i++)
        if (strcmp (mlist[2], encligops[i]) == 0) {
          op = i;
          break;
        }
      if (op < 0)
        error ("! bad ligature op specified");
      if (!strcmp (mlist[0], boundaryname))
        ai = lbound;
      else
        ai = findadobe (mlist[0]);
      if (ai) {
        struct lig *lig;

        if (findadobe (mlist[1]))       /* remove coincident kerns */
          rmkern (mlist[0], mlist[1]);
        if (strcmp (mlist[3], boundaryname) == 0)
          error ("! you can't lig to the boundary character!");
        for (lig = ai->ligs; lig; lig = lig->next)
          if (strcmp (lig->succ, mlist[1]) == 0)
            break; /* we'll re-use this structure */
        if (lig == 0) {
          lig = newlig ();
          lig->succ = newstring (mlist[1]);
          lig->next = ai->ligs;
          ai->ligs = lig;
        }
        lig->sub = newstring (mlist[3]);
        lig->op = op;
        if (strcmp (mlist[1], boundaryname) == 0) {
          lig->boundright = 1;
          if (strcmp (mlist[0], boundaryname) == 0)
            error ("! you can't lig boundarychar boundarychar!");
        } else
          lig->boundright = 0;
      }
    } else
      error ("! bad form in LIGKERN command");
  }
}

static void
letterspace(void)
{
  int i,j;
  struct kern *k;
  struct adobeinfo *ai;
  int *haskern; /* which glyphs are rhs of a kerning pair? */

  haskern = (int *) malloc (nglyphs * sizeof (int));
  for (i=0;i<nglyphs;i++) {
    for (j=0;j<nglyphs;j++) haskern[j] = 0;
    ai = adobechars[i];
    for (k=ai->kerns;k;k=k->next) {
      j = findindex (k->succ);
      if (j>0 && j<nglyphs) {
        /* kern with rbound is NOT modified */
        k->delta += lspace;
        haskern[j] = 1;
      }
    }
    for (j=0;j<nglyphs;j++) if (!haskern[j]) {
      k = newkern();
      k->succ = adobechars[j]->adobename;
      k->delta = lspace;
      k->next = ai->kerns;
      ai->kerns = k;
    }
  }
  free (haskern);
  fontspace += 2 * lspace;
}

static void
extraligkerninfo(void)
{
  int i;
  char *p;
  struct adobeinfo *ai;

  /* with positive letterspacing, remove native ligs unless keepligs
   */
  if (lspace>0 && !keepligs)
    for (i=0;i<nglyphs;i++) adobechars[i]->ligs = NULL;

  /* Boundarychars make things a lot messier than they would be
   * otherwise. A rather long summary:
   * When typesetting, TeX sandwiches words between a left
   * boundarychar and a right boundarychar.
   * It seems sensible to translate space kerns into boundarychar
   * kerns although afm2tfm doesn't do this.
   * Below, we read ligkern info twice: the first time to read
   * a right boundarychar spec, if any, the second time to read everything
   * else. The global loop variable lig_it is consulted by checkligkern.
   * more about boundarychar/boundaryname:
   * rboundarychar is the index of right boundarychar in the tfm;
   * initialized as -1
   * The left boundarychar doesn't need a proper tfm index
   */
  if (lspace>0 && !strcmp (ligoption, "0")) ligoption = "1";
  if (!strcmp (ligoption, "0"))
    return;
  if (!strcmp (ligoption, "1") && encfilename && lspace<=0) {
    sawligkern = 0;
    /* ligkern specs in comments in encoding file? */
    encfilename =
      openin (encfilename, kpse_enc_format, ".enc");
    for (lig_it = 0; lig_it < 2; lig_it++) {
      while (texlive_getline ()) {
        /* search for (ligkern) comment in line */
        for (p = buffer; *p; p++)
          if (*p == '%') {
            checkligkern (p, 1);        /* 2nd param 1: reading .enc file */
            break;
          }
      }
      if (!sawligkern)
        break;     /* read default lig file instead */
      if (!lig_it) {
        if (rboundarychar == -1)
          set_rboundarychar (-1);
        rewind (infile);
      }
    }
    fclose (infile);
    if (sawligkern)
      return;
    else {
      ligfilenames->n = 1;
      ligfilenames->names = malloc (sizeof (char *));
      ligfilenames->names[0] = "default.lig";
    }
  } else if (!strcmp (ligoption, "1")) { /* lspace>0 or no encfile */
    ligfilenames->n = 1;
    ligfilenames->names = malloc (sizeof (char *));
    if (lspace<=0) ligfilenames->names[0] = "default.lig";
    else ligfilenames->names[0] = "defpre.lig";
  }

  /* process ligfilenames struct */
  for (lig_it = 0; lig_it < 2; lig_it++) {
    for (i = 0; i < ligfilenames->n; i++) {
      ligfilename = openin (ligfilenames->names[i],
                            kpse_lig_format, ".lig");
      while (texlive_getline ())
        checkligkern (buffer, 0);       /* 2nd param 0: lig file */
      fclose (infile);
    }
    if (!lig_it && (rboundarychar == -1))
      set_rboundarychar (-1);
  }

  /* optimization: identify glyphs which now have ligs or kerns.
   * Boundarychars: rboundarychar won't get a label in the ligtable,
   * and lboundarychar will be done separately anyhow.
   */
  for (i=0;i<nglyphs;i++) {
    ai = adobechars[i];
    ai->nonstd_lk = (ai->ligs!=NULL || ai->kerns!=NULL);
  }

  if (!lspace) return;

  letterspace();

  /* process post-letterspace ligfiles */
  if (!strcmp (Ligoption, "1")) {
    Ligfilenames->n = 1;
    Ligfilenames->names = malloc (sizeof (char *));
    Ligfilenames->names[0] = "defpost.lig";
  }
  lig_it = 2;
  for (i = 0; i < Ligfilenames->n; i++) {
    ligfilename = openin (Ligfilenames->names[i],
                          kpse_lig_format, ".lig");
    while (texlive_getline ())
      checkligkern (buffer, 0);       /* 2nd param 0: lig file */
    fclose (infile);
  }
}

static void
spaceparms(void)
{
  /* afm2tfm values for fstretch, fshrink, fextra: 200, 100, 111
   * fontinst values: 0.6 * space, 0.24 * space, ?
   * cmr10 values: 0.5 * space, .33 * space, .33 * space
   */
  if (!fixedpitch) {
    if (fstretch==0) fstretch = fontspace / 2;
    if (fshrink==0) fshrink = fontspace / 3;
    if (fextra==0) fextra = fontspace / 3;
  }
}

/*********************************************************
 * debug output of adobeinfo structs */

#ifdef AFMDEBUG
FILE *dmp;
char *dmpname = "afm2pl.dmp";

static void
dumpai(struct adobeinfo *ai)
{
  struct lig *lg;
  struct kern *kr;
  putc ('\n', dmp);
  fprintf (dmp, "adobename %s\n",
           ai->adobename ? ai->adobename : "undefined");
  fprintf (dmp, "adobenum %d\n", ai->adobenum);
  fprintf (dmp, "tfmnum %d\n", ai->tfmnum);
  fprintf (dmp, "width %d\n", ai->width);
  fprintf (dmp, "bbox %d %d %d %d\n", ai->llx, ai->lly, ai->urx,
           ai->ury);
  fprintf (dmp, "nonstd_lk %d\n", ai->nonstd_lk);
  if (!ai->ligs)
    fputs ("no ligs\n", dmp);
  else
    for (lg = ai->ligs; lg; lg = lg->next)
      fprintf (dmp, "lig %s %d %s%s\n",
               lg->succ, lg->op, lg->sub,
               lg->boundright ? " boundarychar" : "");
  if (!ai->kerns)
    fputs ("no kerns\n", dmp);
  else
    for (kr = ai->kerns; kr; kr = kr->next)
      fprintf (dmp, "kern %s %d\n", kr->succ, kr->delta);
}

static void
writedump(void)
{
  int i;
  dmp = fopen (dmpname, W_MODE);
  if (!dmp)
    error ("Cant open dump file");
  if (lbound) {
    fputs ("\nleft boundarychar\n", dmp);
    dumpai (lbound);
  }
  if (rbound) {
    fputs ("\nright boundarychar\n", dmp);
    dumpai (rbound);
  }
  for (i = 0; i < nglyphs; i++)
    if (adobechars[i]) dumpai (adobechars[i]);
    else fprintf (dmp, "\nNo char at slot %d\n", i);

  fputs ("\nBy tfmptrs:\n", dmp);
  for (i = 0; i < 256; i++)
    if (tfmptrs[i]) dumpai (tfmptrs[i]);
    else fprintf (dmp, "\nNo char at slot %d\n", i);
  fclose (dmp);
}
#endif

/*******************************************************************
 * the PL file. */

#define plout(s)  fprintf(outfile, s)
int level;                      /* depth of parenthesis nesting in PL output file */

/* indent */
static void
pllevout(void)
{
  register int l = level;
  while (l--)
    plout ("   ");
}

/* newline plus indent */
static void
pllevnlout(void)
{
  plout ("\n");
  pllevout ();
}

#define ploutln(str) {fprintf(outfile,"%s\n",str);pllevout();}
#define ploutln2(f,s) {fprintf(outfile,f,s);pllevnlout();}
#define ploutln3(f,a,b) {fprintf(outfile,f,a,b);pllevnlout();}
#define ploutln4(f,a,b,c) {fprintf(outfile,f,a,b,c);pllevnlout();}

/* left bracket */
static void
plleft(void)
{
  level++;
  plout ("(");
}

/* right bracket */
static void
plright(void)
{
  level--;
  ploutln (")");
}

/* return string representation for .pl file  of tfmptrs[c]
 * don't forget that TeX doesn't use glyph names.
 * only, if c happens to be a printable ascii char
 * then we gratefully use that fact if we are allowed to.
 * If the encoding moves the printable ascii range around then
 * forceoctal would be a good idea.
 */
char plcharbuf[6];
static char *
plchar(int c)
{
  if (forceoctal == 0 && ISALNUM (c))
    (void) sprintf (plcharbuf, "C %c",
#ifndef VMCMS
                    c);
#else
                    ascii2ebcdic[c]);
#endif
  else
    (void) sprintf (plcharbuf, "O %o", (unsigned) c);
  return (char *) plcharbuf;
}

/* comment string with official glyph name if useful,
 * null string otherwise
 */
char plnamebuf[100];
static char *
plname(int c)
{
  if (!forceoctal && ISALNUM (c)) {
    plnamebuf[0] = 0;
  } else if (c >= 0 && c < 256) {
    sprintf (plnamebuf, " (comment %s)", tfmptrs[c]->adobename);
  }
  return (char *) plnamebuf;
}


/* obuffer: originally unmodified copy of input buffer,
 * now recycled as output buffer
 */
static void
writepl(void)
{
  register int i, j, k;
  int bc, ec;
  register struct adobeinfo *ai;
  register struct lig *nlig;
  register struct kern *nkern;
  struct adobeinfo *asucc, *asub;
  int ht, dt;
  char labeled;
  const char *pp;

  outname = openout (outname, based_on, ".pl");

  /* header */
  {
    char *outbase = newstring (xbasename (outname));
    pp = find_suffix (outbase);
    if (pp)
      outbase[pp - outbase - 1] = 0;
    (void) sprintf (obuffer, "%s%s%s", outbase,
                    (efactor == 1.0 ? "" : "-E"),
                    (slant == 0.0 ? "" : "-S"));
    free (outbase);
  }
  if (strlen (obuffer) > 19) {  /* too long, will retain first 9 and last 10 */
    register char *p, *q;
    for (p = &obuffer[9], q = &obuffer[strlen (obuffer) - 10];
         p < &obuffer[19]; p++, q++)
      *p = *q;
    obuffer[19] = 0;
  }

  /* global parameters */
  ploutln2 ("(FAMILY %s)", obuffer);
  {
    char tbuf[41];
    char *tbp;

    strncpy (tbuf, outencoding->name, 40);
    tbuf[40] = 0;

    if (strlen (tbuf) > 39) {
      error ("Coding scheme too long; shortening to 39 characters.");
      tbuf[39] = 0;
    }
    tbp = tbuf;
    while (*tbp) { *tbp = toupper ((unsigned char)*tbp); tbp++; }
    ploutln2 ("(CODINGSCHEME %s)", tbuf);
  }
  ploutln ("(DESIGNSIZE R 10.0)");
  ploutln ("(DESIGNUNITS R 1000)");
  ploutln ("(COMMENT DESIGNSIZE (1 em) IS IN POINTS)");
  ploutln
    ("(COMMENT OTHER DIMENSIONS ARE MULTIPLES OF DESIGNSIZE/1000)");
  /* Let pltotf compute the checksum. */
  /* ploutln2("(CHECKSUM O %lo)",cksum ^ 0xffffffff) ; */
  if (rboundarychar >= 0)
    ploutln2 ("(BOUNDARYCHAR O %lo)", (unsigned long) rboundarychar);
  plleft ();
  ploutln ("FONTDIMEN");
  ploutln2 ("(SLANT R %f)", newslant);
  ploutln2 ("(SPACE D %d)", fontspace);
  ploutln2 ("(STRETCH D %d)", fstretch);
  ploutln2 ("(SHRINK D %d)", fshrink);
  ploutln2 ("(XHEIGHT D %d)", xheight);
  ploutln2 ("(QUAD D %d)", fquad);
  if (!afm2tfm_compat) ploutln2 ("(EXTRASPACE D %d)", fextra);
  plright ();

  /* beginning and end of char array */
  for (i = 0; i < 256 && tfmptrs[i] == NULL; i++);
  bc = i;
  for (i = 255; i >= 0 && tfmptrs[i] == NULL; i--);
  ec = i;

  /* ligkern table */
  plleft ();
  ploutln ("LIGTABLE");

  /* (left) boundarychar ligskerns */
  ai = lbound;
  labeled = 0;
  for (nlig = ai->ligs; nlig; nlig = nlig->next)
    if (0 != (asucc = findtfm (nlig->succ)))
      if (0 != (asub = findtfm (nlig->sub))) {
        if (!labeled) {
          ploutln ("(LABEL BOUNDARYCHAR)");
          labeled = 1;
        }
        /* handle all encodings of asucc */
        for (k = asucc->tfmnum; k >= 0; k = tfmnext[k])
          ploutln4 ("(%s %s O %o)", plligops[nlig->op],
                    plchar (k), (unsigned) asub->tfmnum);
      }
  for (nkern = ai->kerns; nkern; nkern = nkern->next)
    if (0 != (asucc = findtfm (nkern->succ))) {
      if (!labeled) {
        ploutln ("(LABEL BOUNDARYCHAR)");
        labeled = 1;
      }
      /* handle all encodings of asucc */
      for (k = asucc->tfmnum; k >= 0; k = tfmnext[k]) {
        ploutln4 ("(KRN %s R %d)%s", plchar (k),
                  nkern->delta, plname (k));
      }
    }
  if (labeled)
    ploutln ("(STOP)");

  /* other ligs and kerns */


  for (i = bc; i <= ec; i++)
    if ((ai = tfmptrs[i]) && ai->tfmnum == i && ai->nonstd_lk) {
      /* slot i is filled, points to a not-previously-encoded
       * character, and has ligs and kerns other than
       * standard letterspacing kerns. Do right boundarychar
       * only if it is a real glyph.
       */
      if (!strcmp (ai->adobename, "||"))
        continue;
      labeled = 0;
      /* do ligatures for ai = tfmptrs[i] */
      for (nlig = ai->ligs; nlig; nlig = nlig->next)
        if (0 != (asucc = findtfm (nlig->succ)))
          if (0 != (asub = findtfm (nlig->sub))) {
            /* we found a lig which really belongs in the tfm */
            if (!labeled) {
              /* also take care of all other slots for this char */
              for (j = i; j >= 0; j = tfmnext[j]) {
                ploutln3 ("(LABEL %s)%s", plchar (j), plname (j));
              }
              labeled = 1;
            }
            for (k = asucc->tfmnum; k >= 0; k = tfmnext[k]) {
              ploutln4 ("(%s %s O %o)", plligops[nlig->op],
                        plchar (k), (unsigned) asub->tfmnum);
            }
          }
      /* do kerns for ai = tfmptrs[i] */
      for (nkern = ai->kerns; nkern; nkern = nkern->next)
        if (0 != (asucc = findtfm (nkern->succ))) {
          if (!labeled) {
            for (j = i; j >= 0; j = tfmnext[j]) {
              ploutln3 ("(LABEL %s)%s", plchar (j), plname (j));
            }
            labeled = 1;
          }
          dt = nkern->delta;
          for (k = asucc->tfmnum; k >= 0; k = tfmnext[k]) {
            ploutln4 ("(KRN %s R %d)%s", plchar (k), dt, plname (k));
          }
        }
      if (labeled)
        ploutln ("(STOP)");
    }

  if (lspace) {
    for (i = bc; i <= ec; i++)
      if ((ai = tfmptrs[i]) && !ai->nonstd_lk) {
        /* do all 'standard' glyphs together.
         * no need to check for ligatures.
         * we do check for kerns, though:
         * if there are none, then apparently all space kerns
         * have been tossed out, and there is nothing to do.
         * Either way, we break out of the loop after doing the
         * first glyph with `standard' ligkerns.
         */
      if (!strcmp(ai->adobename,"||")) continue;
      if (!ai->kerns) break;
      for (j = i; j <= ec; j++) if (tfmptrs[j] && !tfmptrs[j]->nonstd_lk)
        ploutln3 ("(LABEL %s)%s", plchar (j), plname (j));
      for (nkern = ai->kerns; nkern; nkern = nkern->next)
        if (0 != (asucc = findtfm (nkern->succ))) {
          dt = nkern->delta;
          for (k = asucc->tfmnum; k >= 0; k = tfmnext[k])
            ploutln4 ("(KRN %s R %d)%s", plchar (k), dt, plname (k));
        }
      ploutln ("(STOP)");
      break;
    }
  }

  plright ();

  /* done with ligkerns; now char metrics */
  for (i = bc; i <= ec; i++)
    if (0 != (ai = tfmptrs[i])) {
      if (!strcmp (ai->adobename, "||"))
        continue;
      plleft ();
      fprintf (outfile, "CHARACTER %s", plchar (i));
      if (*plcharbuf == 'C') {
        ploutln ("");
      } else
        ploutln2 (" (comment %s)", ai->adobename);
      ploutln2 ("(CHARWD R %d)", ai->width);
      if (0 != (ht = ai->ury))
        ploutln2 ("(CHARHT R %d)", ht);
      if (ai->lly)
        ploutln2 ("(CHARDP R %d)", -ai->lly);
      if (ai->urx > ai->width)
        ploutln2 ("(CHARIC R %d)", ai->urx - ai->width);
      plright ();
    }
  if (level)
    error ("! I forgot to match the parentheses");
  fclose (outfile);
}

/*******************************************************************
 * (version and) usage
 */
static void
version(FILE *f)
{
  fputs ("afm2pl(k) 0.7.1\n", f);
#ifdef KPATHSEA
  fprintf (f, "%s\n", kpathsea_version_string);
#endif
  fputs ("Copyright (C) 2002, 2005, 2009 Siep Kroonenberg.\n\
This program is derived from afm2tfm, (C) 2002 Radical Eye Software.\n\
There is NO warranty.  You may redistribute this software\n\
under the terms of the GNU General Public License.\n\
For more information about these matters, see the files\n\
named COPYING and afm2pl.c.\n", f);
}

#define USAGE "\
Convert an Adobe font metric file to a TeX font property list.\n\
\n\
-p ENCFILE          Read/download ENCFILE for the PostScript encoding\n\
-o                  Use octal for all character codes in the pl file\n\
-e REAL             Widen (extend) characters by a factor of REAL\n\
-s REAL             Oblique (slant) characters by REAL, generally <<1\n\
-m INTEGER          Letterspace by INTEGER/1000 em\n\
-V                  Verbose output; i.e. report on missing glyphs\n\
--help              Print this message and exit.\n\
--version           Print version number and exit.\n\n\
See the man page for full documentation.\n\n\
"

static void
afm2pl_usage(FILE *f)
{
  fputs ("Usage: afm2pl [OPTIONS]... FILE[.afm] [FILE[.pl]]\n", f);
  fputs (USAGE, f);
  fputc ('\n', f);
  fputs ("Email bug reports to ntg-afm2pl@ntg.nl\n", f);
}

/**************************************************************
 * parse commandline
 */

/* decode comma-separated list of non-negative integers.
 * initialize everything to -1 i.e. undefined
*/
static int
getnums(char *st, int *nums, int num)
{
  char *p; /* pointer into st */
  int curnum, curindex, ndigits;
  /* curnum: number to be parsed
     curindex: index for nums array
     ndigits: n. of digits found for curnum
  */
  for (curindex=0;curindex<num;curindex++) {
    nums[curindex] = -1;
  }
  for (curnum=0,curindex=0,ndigits=0,p=st;;p++) {
    if (*p==',' || *p==0) {
      /* done with this number */
      if (ndigits>0) /* we found some digits */
        nums[curindex] = curnum;
      curnum = 0;
      curindex++;
      ndigits = 0;
      if (curindex>=num || !*p) break;
    } else if (*p>='0' && *p<='9') {
      curnum = 10*curnum + (*p-'0');
      ndigits++;
    } else {
      error ("! Illegal -f parameter");
    }
  }
  if (!*p) return 1; /* end of string reached: no problems */
  else return 0;
}

/* split string on commas into strings; disregard empty strings */
static struct nstrings *
getoutnames(const char *st, struct nstrings *onames)
{
  char *argcopy;
  unsigned i;
  int j, inpart;
  argcopy = (char *) malloc (strlen (st) + 1);
  strcpy (argcopy, st);
  inpart = 0;      /* cursor not inside a constituing substring */
  for (i = 0, onames->n = 0; i < strlen (st); i++) {
    if (argcopy[i] == ',') {
      argcopy[i] = 0;
      inpart = 0;
    } else if (!inpart) {
      inpart = 1;
      onames->n++;
    }
    /* !=',', inpart: do nothing */
  }
  onames->names = (const char **) malloc (onames->n * sizeof (char *));
  inpart = 0;
  for (i = 0, j = 0; i < strlen (st); i++) {
    if (argcopy[i] == 0)
      inpart = 0;
    else if (!inpart) {
      onames->names[j++] = argcopy + i;
      inpart = 1;
    }
  }
  return onames;
}

/* call this when an option requires an argument */
#define CHECKARG3 if (argc < 3) { afm2pl_usage(stderr); exit(1); }

static void
readargs(int argc, char **argv)
{
  register int i;
  int fdims[5];

  /* skip argv[0] and look at the rest. */
  argv++;
  argc--;

  if (argc <= 0 || !strcmp (argv[0], "--help") ||
    !strcmp (argv[0], "-help") || !strcmp (argv[0], "-h")) {
    afm2pl_usage (stdout);
    exit (0);
  }

  if (!strcmp (argv[0], "--version") ||
    !strcmp (argv[0], "-version") || !strcmp (argv[0], "-v")) {
    version (stdout);
    exit (0);
  }

  /* allocate structs for ligkern filenames */
  ligfilenames = (struct nstrings *) mymalloc
    ((unsigned long) sizeof (struct nstrings));
  Ligfilenames = (struct nstrings *) mymalloc
    ((unsigned long) sizeof (struct nstrings));

  /* looping: advance argv and decrement argc to match unprocessed
   * command-line arguments.
   * After the options, we need at least an afm filename,
   * which will be handled AFTER this loop.
   */

  while (argc > 0 && *argv[0] == '-') {
    i = argv[0][1];
    /* I don't understand what this is about.
     * The comment below suggests that it is VM/CMS-specific
     * so I comment it out for other OS-es. [SK]
     */
#ifdef VMCMS
    if (i == '/')
      i = argv[0][2] - 32;      /* /a ==> A for VMS */
#endif
    switch (i) {
    case 'e':
      efactor = 1.0;
      CHECKARG3
        if (sscanf (argv[1], "%f", &efactor) == 0 || efactor < 0.01)
        error ("! Bad extension factor");
      efactorparam = argv[1];
      argv += 2;
      argc -= 2;
      break;
    case 's':
      CHECKARG3 if (sscanf (argv[1], "%f", &slant) == 0)
        error ("! Bad slant parameter");
      slantparam = argv[1];
      argv += 2;
      argc -= 2;
      break;
    case 'm':
      CHECKARG3 if (sscanf (argv[1], "%d", &lspace) == 0)
        error ("! Bad letterspacing parameter");
      lspaceparam = argv[1];
      if (lspace > 0)
        keepligs = 0;
      argv += 2;
      argc -= 2;
      break;
    case 'p':
      CHECKARG3 encfilename = argv[1];
      argv += 2;
      argc -= 2;
      break;
    case 'f':
      CHECKARG3
      if (!strcmp (argv[1], "afm2tfm")) {
        afm2tfm_compat = 1;
      } else if (!strcmp (argv[1], "afm2tfm")) {
        afm2tfm_compat = 1;
      } else {
        if (!getnums (argv[1], fdims, 5))
          error ("!Parsing error in argument of -f");
        fstretch = fdims[0]; fshrink = fdims[1]; fextra = fdims[2];
        fquad = fdims[3]; fontspace = fdims[4];
      }
      argv += 2;
      argc -= 2;
      break;
    case 'l':
      CHECKARG3 ligoption = argv[1];
      if (strcmp (ligoption, "0") && strcmp (ligoption, "1")) {
        getoutnames (ligoption, ligfilenames);
      }
      argv += 2;
      argc -= 2;
      break;
    case 'L':
      CHECKARG3 Ligoption = argv[1];
      if (strcmp (Ligoption, "0") && strcmp (Ligoption, "1")) {
        getoutnames (Ligoption, Ligfilenames);
      }
      argv += 2;
      argc -= 2;
      break;
    case 'o':
      forceoctal = 1;
      argv += 1;
      argc -= 1;
      break;
    case 'k':
      keepligs = 1;
      argv += 1;
      argc -= 1;
      break;
    case 'n':
      no_prefix = 1;
      argv += 1;
      argc -= 1;
      break;
    case 'V':
      verbose = 1;
      argv += 1;
      argc -= 1;
      break;
    default:
      (void) fprintf (stderr,
                      "Unknown option %s %s will be ignored.\n",
                      argv[0], argv[1]);
      argv += 2;
      argc -= 2;
    }
  }

  /* end of loop. Remainder: name of afm file and possibly pl file */
  afmname = argv[0];

  if ((argc < 1) || (argc > 2)) {
    error ("! need one or two non-option arguments");
    afm2pl_usage (stderr);
  }

  if (argc == 1) {
    outname = afmname;
    based_on = 1;
  } else {
    outname = argv[1];
    based_on = 0;
  }
}

/* This routine prints out the line that needs to be added to psfonts.map.
 */
static void
conspsfonts(void)
{
  char *p;
  const char *q;

  /* TeX fontname is file basename without path or extension */
  p = newstring (xbasename (outname));
  q = find_suffix (p);
  if (q)
    p[q - p - 1] = 0;
  openout (p, 0, ".map");
  (void) fprintf (outfile, "%s %s", p, fontname);
  free (p);
  if (slantparam || efactorparam || encfilename) {
    (void) fprintf (outfile, " \"");
    if (slantparam)
      (void) fprintf (outfile, " %s SlantFont", slantparam);
    if (efactorparam)
      (void) fprintf (outfile, " %s ExtendFont", efactorparam);
    if (encfilename)
      (void) fprintf (outfile, " %s ReEncodeFont", outencoding->name);
    (void) fprintf (outfile, " \"");
    if (encfilename) {
      const char *base = xbasename (encfilename);
      (void) fprintf (outfile, " <%s", base);
    }
  }
  p = newstring (xbasename (afmname));
  q = find_suffix (p);
  if (q)
    p[q - p - 1] = 0;
  (void) fprintf (outfile, " <%s.pfb", p);
  free (p);
  (void) fprintf (outfile, "\n");
  fclose (outfile);
}

/********************************************************
 * main program
 */

#ifndef VMS
int
#endif
main(int argc, char **argv)
{

#ifdef KPATHSEA
  kpse_set_program_name (argv[0], "afm2pl");

  if (argc == 1) {
    fputs ("afm2pl: Need at least one file argument.\n", stderr);
    fputs ("Try `afm2pl --help' for more information.\n", stderr);
    exit (1);
  }
  if (argc == 2) {
    if (strcmp (argv[1], "--help") == 0) {
      afm2pl_usage (stdout);
      exit (0);
    } else if (strcmp (argv[1], "--version") == 0) {
      version (stdout);
      exit (0);
    }
  }
#endif /* KPATHSEA */
  readargs (argc, argv);
  readadobe ();
  changeadobe ();
  readencoding ();
  extraligkerninfo ();  /* loop over lig files and lines in lig files */
  spaceparms ();
#ifdef AFMDEBUG
  writedump ();
#endif
  writepl ();
  conspsfonts ();
  return -missingchars;
}