File: ftifi.c

package info (click to toggle)
freetype 1.3.1-1
  • links: PTS
  • area: main
  • in suites: potato
  • size: 6,652 kB
  • ctags: 6,860
  • sloc: ansic: 47,576; pascal: 13,773; sh: 7,513; makefile: 786; cpp: 351; csh: 53; perl: 13
file content (3209 lines) | stat: -rw-r--r-- 119,581 bytes parent folder | download | duplicates (5)
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
/*                                                                         */
/*             OS/2 Font Driver using the FreeType library                 */
/*                                                                         */
/*       Copyright (C) 1997, 1998 Michal Necasek <mike@mendelu.cz>         */
/*       Copyright (C) 1997, 1998 David Turner <turner@email.ENST.Fr>      */
/*       Copyright (C) 1997, 1998 International Business Machines          */
/*                                                                         */
/*       Version: 0.9.90 (Beta)                                            */
/*                                                                         */
/* This source is to be compiled with IBM VisualAge C++ 3.0 or possibly    */
/* Watcom C/C++ 10.0 or higher (Wactom doesn't quite work yet).            */
/* Other compilers may actually work too but don't forget this is NOT a    */
/* normal DLL but rather a subsystem DLL. That means it shouldn't use      */
/* the usual C library as it has to run without runtime environment.       */
/* VisualAge provides a special subsystem version of the run-time library. */
/* All this is of course very compiler-dependent. See makefiles for        */
/* discussion of switches used.                                            */
/*                                                                         */
/*  Implemantation Notes:                                                  */
/*                                                                         */
/* Note #1: As a consequence of this being a subsystem librarary, I had to */
/*   slightly modify the FreeType source, namely ttmemory.c and ttfile.c.  */
/*   FreeType/2 now allocates several chunks of memory and uses them as a  */
/*   heap. Note that memory allocation should use TTAlloc(), possibly      */
/*   directly SSAllocMem(). malloc() is unusable here and it doesn't work  */
/*   at all (runtime library isn't even initialized). See ttmemory.c for   */
/*   more info.                                                            */
/*    In ttfile.c I had to change all fopen(), fseek()... calls            */
/*   to OS/2 API calls (DosOpen, DosSetFilePtr...) because without proper  */
/*   runtime environment a subsystem DLL cannot use std C library calls.   */
/*                                                                         */
/* Note #2: On exit of each function reading from font file the API        */
/*   TT_Flush_Stream() must be called. This is because file handles opened */
/*   by this DLL actually belong to the calling process. As a consequence  */
/*    a) it's easy to run out of file handles, which results in really     */
/*       very nasty behavior and/or crashes. This could be solved by       */
/*       increased file handles limit, but cannot because                  */
/*    b) it is impossible to close files open by another process and       */
/*       therefore the fonts cannot be properly uninstalled (you can't     */
/*       delete them while the're open by other process)                   */
/*   The only solution I found is very simple - just close the file before */
/*   exiting a DLL function. This ensures files are not left open across   */
/*   processes and other problems.                                         */
/*                                                                         */
/* Note #3: The whole business with linked lists is aimed at lowering      */
/*   memory consumption drastically. If you install 50 TT fonts, OS/2      */
/*   opens all of them at startup. Even if you never use them, they take   */
/*   up at least over 1 Meg memory. With certain fonts the consumption can */
/*   easily go over several MB. We limit such waste of memory by only      */
/*   actually keeping open several typefaces most recently used. Their     */
/*   number can be set via entry in OS2.INI.                               */
/*                                                                         */
/* For Intelligent Font Interface (IFI) specification please see IFI32.TXT */

#ifndef  __IBMC__
   #ifndef __WATCOMC__
      #error "This source requires IBM VisualAge C++ or Watcom C/C++"
   #endif
#endif

/* Defining the following uses UCONV.DLL instead of the built-in  */
/* translation tables. This code should work on any Warp 4 and    */
/* Warp 3 w/ FixPak 35(?) and above                               */
/* Note: this should be defined before FTIFI.H is #included       */
#undef  USE_UCONV

#define INCL_WINSHELLDATA   /* for accessing OS2.INI */
#define INCL_DOSMISC
#define INCL_DOSNLS
#define INCL_DOSPROCESS
#define INCL_GRE_DCS
#define INCL_GRE_DEVSUPPORT
#define INCL_DDIMISC
#define INCL_IFI
#include <os2.h>
#include <pmddi.h>     /* SSAllocmem(), SSFreemem() and more */

#ifdef USE_UCONV       /* uconv.h isn't always available */
#include <uconv.h>
#endif  /* USE_UCONV */

#include <string.h>
#include <stdlib.h>         /* min and max macros */

#define  _syscall  _System  /* the IFI headers don't compile without it */

#include "32pmifi.h"        /* IFI header             */
#include "freetype.h"       /* FreeType header        */
#include "ftxkern.h"        /* kerning extension      */
#include "ftxwidth.h"       /* glyph width extension  */
#include "ftifi.h"          /* xlate table            */


/* For the sake of Netscape's text rendering bugs ! */
#define NETSCAPE_FIX

/* Create 'fake' Roman face for Times New Roman (to mimic PMATM's */
/* behaviour                                                      */
#define FAKE_TNR

/* (indirectly) exported functions */
LONG _System ConvertFontFile(PSZ pszSrc, PSZ pszDestDir, PSZ pszNewName);
HFF  _System LoadFontFile(PSZ pszFileName);
LONG _System UnloadFontFile(HFF hff);
LONG _System QueryFaces(HFF hff, PIFIMETRICS pifiMetrics, ULONG cMetricLen,
                        ULONG cFountCount, ULONG cStart);
HFC  _System OpenFontContext(HFF hff, ULONG ulFont);
LONG _System SetFontContext(HFC hfc, PCONTEXTINFO pci);
LONG _System CloseFontContext(HFC hfc);
LONG _System QueryFaceAttr(HFC hfc, ULONG iQuery, PBYTE pBuffer,
                           ULONG cb, PGLYPH pagi, GLYPH giStart);
LONG _System QueryCharAttr(HFC hfc, PCHARATTR pCharAttr,
                           PBITMAPMETRICS pbmm);
LONG _System QueryFullFaces(HFF hff, PVOID pBuff, PULONG buflen,
                            PULONG cFontCount, ULONG cStart);

FDDISPATCH fdisp = {        /* Font driver dispatch table */
   LoadFontFile,
   QueryFaces,
   UnloadFontFile,
   OpenFontContext,
   SetFontContext,
   CloseFontContext,
   QueryFaceAttr,
   QueryCharAttr,
   NULL,     /* this one is no more used, only the spec fails to mention it */
   ConvertFontFile,
   QueryFullFaces
};



/****************************************************************************/
/* the single exported entry point; this way is faster than exporting every */
/* single function and a bit more flexible                                  */
/*                                                                          */
#pragma export (fdhdr, "FONT_DRIVER_DISPATCH_TABLE", 1)
FDHEADER   fdhdr =
{  /* Font driver Header */
   sizeof(FDHEADER),
   "OS/2 FONT DRIVER",                  /* do not change */
   "TrueType (Using FreeType Engine)",  /* description up to 40 chars */
   IFI_VERSION20,                       /* version */
   0,                                   /* reserved */
   &fdisp
};


/****************************************************************************/
/* some debug macros and functions. the debug version logs system requests  */
/* to the file C:\FTIFI.LOG                                                 */
/*                                                                          */
#ifdef DEBUG
  HFILE LogHandle = NULLHANDLE;
  ULONG Written   = 0;
  char  log[2048] = "";
  char  buf[2048] = "";


char*  itoa10( int i, char* buffer ) {
    char*  ptr  = buffer;
    char*  rptr = buffer;
    char   digit;

    if (i == 0) {
      buffer[0] = '0';
      buffer[1] =  0;
      return buffer;
    }

    if (i < 0) {
      *ptr = '-';
       ptr++; rptr++;
       i   = -i;
    }

    while (i != 0) {
      *ptr = (char) (i % 10 + '0');
       ptr++;
       i  /= 10;
    }

    *ptr = 0;  ptr--;

    while (ptr > rptr) {
      digit = *ptr;
      *ptr  = *rptr;
      *rptr = digit;
       ptr--;
       rptr++;
    }

    return buffer;
}

  #define  COPY(s)     strcpy(log, s)
  #define  CAT(s)      strcat(log, s)
  #define  CATI(v)     strcat(log, itoa10( (int)v, buf ))
  #define  WRITE       DosWrite(LogHandle, log, strlen(log), &Written)

  #define  ERET1(label) { COPY("Error at ");  \
                          CATI(__LINE__);    \
                          CAT("\r\n");       \
                          WRITE;             \
                          goto label;        \
                       }

  #define  ERRRET(e)   { COPY("Error at ");  \
                          CATI(__LINE__);    \
                          CAT("\r\n");       \
                          WRITE;             \
                          return(e);         \
                       }


#else

  #define  COPY(s)
  #define  CAT(s)
  #define  CATI(v)
  #define  WRITE

  #define  ERET1(label)  goto label;

  #define  ERRRET(e)  return(e);

#endif /* DEBUG */


/****************************************************************************/
/*                                                                          */
/* 'engine' :                                                               */
/*                                                                          */
/*  The FreeType engine instance. Although this is a DLL, it isn't          */
/*  supposed to be shared by apps, as it is only called by the OS/2 GRE.    */
/*  This means that there is no need to bother with reentrancy/thread       */
/*  safety, which aren't supported by FreeType 1.0 anyway.                  */
/*                                                                          */
TT_Engine engine;

/****************************************************************************/
/*                                                                          */
/* TList and TListElement :                                                 */
/*                                                                          */
/*  simple structures used to implement a doubly linked list. Lists are     */
/*  used to implement the HFF object lists, as well as the font size and    */
/*  outline caches.                                                         */
/*                                                                          */

typedef struct _TListElement  TListElement, *PListElement;

struct _TListElement
{
  PListElement  next;    /* next element in list - NULL if tail     */
  PListElement  prev;    /* previous element in list - NULL if head */
  long          key;     /* value used for searches                 */
  void*         data;    /* pointer to the listed/cached object     */
};

typedef struct _TList  TList, *PList;
struct _TList
{
  PListElement  head;    /* first element in list - NULL if empty */
  PListElement  tail;    /* last element in list - NULL if empty  */
  int           count;   /* number of elements in list            */
};

static  PListElement  free_elements = 0;

#if 0
/****************************************************************************/
/*                                                                          */
/* TGlyph_Image :                                                           */
/*                                                                          */
/*  structure used to store a glyph's attributes, i.e. outlines and metrics */
/*  Note that we do not cache bitmaps ourselves for the moment.             */
/*                                                                          */
typedef struct _TGlyph_Image  TGlyph_Image,  *PGlyph_Image;

struct _TGlyph_Image
{
  PListElement      element;  /* list element for this glyph image */
  TT_Glyph_Metrics  metrics;
  TT_Outline        outline;
};
#endif


/****************************************************************************/
/*                                                                          */
/* TFontFace :                                                              */
/*                                                                          */
/* a structure related to an open font face. It contains data for each of   */
/* possibly several faces in a .TTC file.                                   */

typedef struct _TFontFace  TFontFace, *PFontFace;

struct _TFontFace
{
   TT_Face       face;            /* handle to actual FreeType face object  */
   TT_Glyph      glyph;           /* handle to FreeType glyph container     */
   TT_CharMap    charMap;         /* handle to FreeType character map       */
   TT_Kerning    directory;       /* kerning directory                      */
   USHORT        *widths;         /* glyph width cache for large fonts      */
   USHORT        *kernIndices;    /* reverse translation cache for kerning  */
   LONG          em_size;         /* points per em square                   */
   ULONG         flags;           /* various FC_* flags (like FC_FLAG_FIXED)*/
#if 0   /* not now */
   TList         sizes;           /* list of live child font sizes          */
#endif
   LONG          charMode;        /* character translation mode :           */
                                  /*   0 = Unicode to UGL                   */
                                  /*   1 = Symbol (no translation)          */
                                  /*   2 = Unicode w/o translation          */
};


/****************************************************************************/
/*                                                                          */
/* TFontFile :                                                              */
/*                                                                          */
/* a structure related to an open font file handle. All TFontFiles are      */
/* kept in a simple linked list. There can be several faces in one font.    */
/* Face(s) information is stored in a variable-length array of TFontFaces.  */
/* A single TFontFile structure exactly corresponds to one HFF.             */

typedef struct _TFontFile  TFontFile, *PFontFile;

struct _TFontFile
{
   PListElement  element;         /* list element for this font face        */
   HFF           hff;             /* HFF handle used from outside           */
   CHAR          filename[260];   /* font file name                         */
   LONG          ref_count;       /* number of times this font file is open */
   ULONG         flags;           /* various FL_* flags                     */
   ULONG         numFaces;        /* number of faces in a file (normally 1) */
   TFontFace     *faces;          /* array of FontFace structures           */
};


/* Flag : The font face has a fixed pitch width */
#define FC_FLAG_FIXED_WIDTH      1

/* Flag : Effectively duplicated  FL_FLAG_DBCS_FILE. This info is    */
/*       kept twice for simplified access                            */
#define FC_FLAG_DBCS_FACE        2

/* Flag : This face is an alias */
#define FL_FLAG_FAKE_ROMAN       8

/* Flag : The font file has a live FreeType face object */
#define FL_FLAG_LIVE_FACE        16

/* Flag : A font file's face has a context open - DON'T CLOSE IT! */
#define FL_FLAG_CONTEXT_OPEN     32

/* Flag : This file has been already opened previously*/
#define FL_FLAG_ALREADY_USED     64

/* Flag : This is a font including DBCS characters; this also means  */
/*       the font driver presents to the system a second, vertically */
/*       rendered, version of this typeface with name prepended by   */
/*       an '@' (used in horizontal-only word processors)            */
/* Note : For TTCs, the whole collection is either DBCS or not. I've */
/*       no idea if there are any TTCs with both DBCS and non-DBCS   */
/*       faces. It's possible, but sounds unlikely.                  */
#define FL_FLAG_DBCS_FILE        128

/* Note, we'll only keep the first max_open_files files with opened */
/* FreeType objects/instances..                                     */
int  max_open_files = 10;

/* number of processes using the font driver; used by the init/term */
/* routine                                                          */
ULONG  ulProcessCount = 0;

/* the list of live faces */
static TList  liveFiles  = { NULL, NULL, 0 };

/* the list of sleeping faces */
static TList  idleFiles = { NULL, NULL, 0 };

/****************************************************************************/
/*                                                                          */
/* TFontSize :                                                              */
/*                                                                          */
/*  a structure related to a opened font context (a.k.a. instance or        */
/*  transform/pointsize). It exactly corresponds to a HFC.                  */
/*                                                                          */

typedef struct _TFontSize  TFontSize, *PFontSize;

struct _TFontSize
{
   PListElement  element;       /* List element for this font size          */
   HFC           hfc;           /* HFC handle used from outside             */
   TT_Instance   instance;      /* handle to FreeType instance              */
   BOOL          transformed;   /* TRUE = rotation/shearing used (rare)     */
   BOOL          vertical;      /* TRUE = vertically rendered DBCS face     */
   TT_Matrix     matrix;        /* transformation matrix                    */
   PFontFile     file;          /* HFF this context belongs to              */
   ULONG         faceIndex;     /* index of face in a font (for TTCs)       */
/* TList         outlines;*/    /* outlines cache list                      */
};

/****************************************************************************/
/* array of font context handles. Note that there isn't more than one font  */
/* context open at any time anyway, but we want to be safe..                */
/*                                                                          */
#define MAX_CONTEXTS  5

static TFontSize  contexts[MAX_CONTEXTS]; /* this is rather too much */


/****************************************************************************/
/* few globals used for NLS                                                 */
/*                                                                          */
/* Note: most of the internationalization (I18N) code was kindly provided   */
/*  by Ken Borgendale and Marc L Cohen from IBM (big thanks!). I also       */
/*  received help from Tetsuro Nishimura from IBM Japan.                    */
/*  I was also unable to test the I18N code on actual Japanese, Chinese...  */
/*  etc. systems. But it might work.                                        */
/*                                                                          */

static ULONG  ScriptTag = -1;
static ULONG  LangSysTag = -1;
static ULONG  iLangId = TT_MS_LANGID_ENGLISH_UNITED_STATES; /* language ID  */
static ULONG  uLastGlyph = 255;                  /* last glyph for language */
static PSZ    pGlyphlistName = "SYMBOL";         /* PM383, PMJPN, PMKOR.... */
static BOOL   isGBK = TRUE;                      /* only used for Chinese   */
static ULONG  ulCp[2] = {1};                     /* codepages used          */
static UCHAR  DBCSLead[12];                      /* DBCS lead byte table    */

/* rather simple-minded test to decide if given glyph index is a 'halfchar',*/
/* i.e. Latin character in a DBCS font which is _not_ to be rotated         */
#define is_HALFCHAR(_x)  ((_x) < 0x0400)


/****************************************************************************/
/*                                                                          */
/* interfaceSEId:                                                           */
/*                                                                          */
/* interfaceSEId (Interface-specific Encoding Id) determines what encoding  */
/* the font driver should use if a font includes a Unicode encoding.        */
/*                                                                          */
LONG    interfaceSEId(TT_Face face, BOOL UDCflag, LONG encoding);

/****************************************************************************/
/*                                                                          */
/* LookUpName :                                                             */
/*                                                                          */
/* this function tries to find M$ English name for a face                   */
/* length is limited to FACESIZE (defined by OS/2); returns NULL if         */
/* unsuccessful. warning: the string gets overwritten on the next           */
/* invocation                                                               */
/*                                                                          */
/* TODO: needs enhancing for I18N                                           */
static  char*  LookupName(TT_Face face,  int index );


/****************************************************************************/
/*                                                                          */
/* GetCharMap :                                                             */
/*                                                                          */
/* get suitable charmap from font                                           */
/*                                                                          */
static  ULONG GetCharmap(TT_Face face);


/****************************************************************************/
/*                                                                          */
/* GetOutlineLen :                                                          */
/*                                                                          */
/* get # of bytes needed for glyph outline                                  */
/*                                                                          */
static  int GetOutlineLen(TT_Outline *ol);


/****************************************************************************/
/*                                                                          */
/* GetOutline :                                                             */
/*                                                                          */
/* get glyph outline in PM format                                           */
/*                                                                          */
static  int GetOutline(TT_Outline *ol, PBYTE pb);



/****************************************************************************/
/*                                                                          */
/* IsDBCSChar :                                                             */
/*                                                                          */
/* Returns TRUE if character is first byte of a DBCS char, FALSE otherwise  */
/*                                                                          */
BOOL IsDBCSChar(UCHAR c)
{
    ULONG       i;

    for (i = 0; DBCSLead[i] && DBCSLead[i+1]; i += 2)
        if ((c >= DBCSLead[i]) && (c <= DBCSLead[i+1]))
            return TRUE;
    return FALSE;
}


/****************************************************************************/
/*                                                                          */
/* TT_Alloc & TT_Free :                                                     */
/*                                                                          */
/* The following two functions are declared here because including          */
/* the entire ttmemory.h creates more problems than it solves               */
/*                                                                          */
TT_Error  TT_Alloc( long  Size, void**  P );
TT_Error  TT_Free( void**  P );
TT_Error  TTMemory_Init(void);

static  TT_Error  error;

#define  ALLOC( p, size )  TT_Alloc( (size), (void**)&(p) )
#define  FREE( p )         TT_Free( (void**)&(p) )

/****************************************************************************/
/*                                                                          */
/* New_Element :                                                            */
/*                                                                          */
/*   return a fresh list element. Either new or recycled.                   */
/*   returns NULL if out of memory.                                         */
/*                                                                          */
static  PListElement   New_Element( void )
{
  PListElement e = free_elements;

  if (e)
    free_elements = e->next;
  else
  {
    if ( ALLOC( e, sizeof(TListElement) ) )
      return NULL;
  }
  e->next = e->prev = e->data = NULL;
  e->key  = 0;

  return e;
}

/****************************************************************************/
/*                                                                          */
/*  Done_Element :                                                          */
/*                                                                          */
/*    recycles an old list element                                          */
/*                                                                          */
static  void  Done_Element( PListElement  element )
{
  element->next = free_elements;
  free_elements = element;
}

/****************************************************************************/
/*                                                                          */
/*  List_Insert :                                                           */
/*                                                                          */
/*    inserts a new object at the head of a given list                      */
/*    returns 0 in case of success, -1 otherwise.                           */
/*                                                                          */
static  int  List_Insert( PList  list,  PListElement  element )
{
  if (!list || !element)
    return -1;

  element->next = list->head;

  if (list->head)
    list->head->prev = element;

  element->prev = NULL;
  list->head    = element;

  if (!list->tail)
    list->tail = element;

  list->count++;
  return 0;
}

/****************************************************************************/
/*                                                                          */
/*  List_Remove :                                                           */
/*                                                                          */
/*    removes an element from its list. Returns 0 in case of success,       */
/*    -1 otherwise. WARNING : this function doesn't check that the          */
/*    element is part of the list.                                          */
/*                                                                          */
static  int  List_Remove( PList  list,  PListElement  element )
{
  if (!element)
    return -1;

  if (element->prev)
    element->prev->next = element->next;
  else
    list->head = element->next;

  if (element->next)
    element->next->prev = element->prev;
  else
    list->tail = element->prev;

  element->next = element->prev = NULL;
  list->count --;
  return 0;
}

/****************************************************************************/
/*                                                                          */
/*  List_Find :                                                             */
/*                                                                          */
/*    Look for a given object with a specified key. Returns NULL if the     */
/*    list is empty, or the object wasn't found.                            */
/*                                                                          */
static  PListElement  List_Find( PList  list, long  key )
{
  static PListElement  cur;

  for ( cur=list->head; cur; cur = cur->next )
    if ( cur->key == key )
      return cur;

  /* not found */
  return NULL;
}

/****************************************************************************/
/*                                                                          */
/* Sleep_FontFile :                                                         */
/*                                                                          */
/*   closes a font file's FreeType objects to leave room in memory.         */
/*                                                                          */
static  int  Sleep_FontFile( PFontFile  cur_file )
{
  int  i;

  if (!(cur_file->flags & FL_FLAG_LIVE_FACE))
    ERRRET(-1);  /* already asleep */

  /* is this face in use?  */
  if (cur_file->flags & FL_FLAG_CONTEXT_OPEN) {
     /* move face to top of the list */
     if (List_Remove( &liveFiles, cur_file->element ))
        ERRRET(-1);
     if (List_Insert( &liveFiles, cur_file->element ))
        ERRRET(-1);

     cur_file = (PFontFile)(liveFiles.tail->data);
  }

  /* remove the face from the live list */
  if (List_Remove( &liveFiles, cur_file->element ))
     ERRRET(-1);

  /* add it to the sleep list */
  if (List_Insert( &idleFiles, cur_file->element ))
    ERRRET(-1);

  /* deactivate its objects - we ignore errors there */
  for (i = 0; i < cur_file->numFaces; i++) {
     TT_Done_Glyph( cur_file->faces[i].glyph );
     TT_Close_Face( cur_file->faces[i].face );
  }
  cur_file->flags  &= ~FL_FLAG_LIVE_FACE;

  return 0;
}

/****************************************************************************/
/*                                                                          */
/* Wake_FontFile :                                                          */
/*                                                                          */
/*   awakes a font file, and reloads important data from disk.              */
/*                                                                          */
static  int  Wake_FontFile( PFontFile  cur_file )
{
  static TT_Face              face;
  static TT_Glyph             glyph;
  static TT_CharMap           cmap;
  static TT_Face_Properties   props;
  static PFontFace            cur_face;
  ULONG                       encoding, i;

  if (cur_file->flags & FL_FLAG_LIVE_FACE)
    ERRRET(-1);  /* already awoken !! */

  /* OK, try to activate the FreeType objects */
  error = TT_Open_Face(engine, cur_file->filename, &face);
  if (error)
  {
     COPY( "Error while opening " ); CAT( cur_file->filename );
     CAT( ", error code = " ); CATI( error ); CAT( "\r\n" ); WRITE;
     return -1; /* error, can't open file                 */
                /* XXX : should set error condition here! */
  }

  /* Create a glyph container for it */
  error = TT_New_Glyph( face, &glyph );
  if (error)
  {
     COPY( "Error while creating container for " ); CAT( cur_file->filename );
     CAT( ", error code = " ); CATI( error ); CAT( "\r\n" ); WRITE;
     goto Fail_Face;
  }

  /*  now get suitable charmap for this font */
  encoding = GetCharmap(face);
  error = TT_Get_CharMap(face, encoding & 0xFFFF, &cmap);
  if (error)
  {
     COPY( "Error: No char map in " ); CAT(  cur_file->filename );
     CAT(  "\r\n" ); WRITE;
     goto Fail_Glyph;
  }

  /* Get face properties. Necessary to find out number of fonts for TTCs */
  TT_Get_Face_Properties(face, &props);

  /* all right, now remove the face from the sleep list */
  if (List_Remove( &idleFiles, cur_file->element ))
    ERET1( Fail_Glyph );

  /* add it to the live list */
  if (List_Insert( &liveFiles, cur_file->element ))
    ERET1( Fail_Glyph );

  /* If the file is a TTC, the first face is now opened successfully.     */

  cur_file->numFaces = props.num_Faces;

  /* Now allocate memory for face data (one struct for each face in TTC). */
  if (cur_file->faces == NULL) {
     if (ALLOC(cur_face, sizeof(TFontFace) * cur_file->numFaces))
        ERET1( Fail_Glyph );

     cur_file->faces  = cur_face;
  }
  else
     cur_face = cur_file->faces;

  cur_face->face      = face;  /* possibly first face in a TTC */
  cur_face->glyph     = glyph;
  cur_face->charMap   = cmap;
  cur_file->flags    |= FL_FLAG_LIVE_FACE;


  if (!(cur_file->flags & FL_FLAG_ALREADY_USED)) {
     cur_face->charMode  = encoding >> 16;  /* Unicode, Symbol, ... */
     cur_face->em_size   = props.header->Units_Per_EM;

     /* if a face contains over 1024 glyphs, assume it's a DBCS font - */
     /* VERY probable                                                  */
     TT_Get_Face_Properties(cur_face->face, &props);

     if (props.num_Glyphs > 1024) {
        cur_file->flags |= FL_FLAG_DBCS_FILE;
        cur_face->flags |= FC_FLAG_DBCS_FACE;
     }

     cur_face->widths    = NULL;
     cur_face->kernIndices = NULL;
  }
  /* load kerning directory, if any */
  error = TT_Get_Kerning_Directory(face, &(cur_face->directory));
  if (error)
     cur_face->directory.nTables = 0; /* indicates no kerning in font */

  TT_Flush_Face(face);    /* this is important !  */

  /* open remaining faces if this font is a TTC */
  for (i = 1; i < cur_file->numFaces; i++) {
     error = TT_Open_Collection(engine, cur_file->filename,
                                i, &face);
     if (error)
        return -1;   /* TODO: handle bad TTCs more tolerantly */

     error = TT_New_Glyph( face, &glyph );
     if (error)
        ERET1(Fail_Face);

     encoding = GetCharmap(face);
     error = TT_Get_CharMap(face, encoding & 0xFFFF, &cmap);
     if (error)
        ERET1(Fail_Glyph);

     cur_face = &(cur_file->faces[i]);

     cur_face->face     = face;
     cur_face->glyph    = glyph;
     cur_face->charMap  = cmap;

     if (!(cur_file->flags & FL_FLAG_ALREADY_USED)) {
        cur_face->em_size  = props.header->Units_Per_EM;
        cur_face->charMode = encoding >> 16;  /* 0 - Unicode; 1 - Symbol */

        if (cur_file->flags & FL_FLAG_DBCS_FILE)
           cur_face->flags |= FC_FLAG_DBCS_FACE;

        cur_face->widths    = NULL;
        cur_face->kernIndices = NULL;
     }

     /* load kerning directory, if any */
     error = TT_Get_Kerning_Directory(face, &(cur_face->directory));
     if (error)
        cur_face->directory.nTables = 0; /* indicates no kerning in font */
  }

  cur_file->flags    |= FL_FLAG_ALREADY_USED; /* indicates some fields need no re-init */

  error = TT_Flush_Face(face);    /* this is important !           */
  if (error) {
     COPY("Error flushing face\r\n"); WRITE;
  }

  return 0;    /* everything is in order, return 0 == success */

Fail_Glyph:
  /* This line isn't really necessary, because the glyph container */
  /* would be destroyed by the following TT_Close_Face anyway. We  */
  /* however use it for the sake of orthodoxy                      */
  TT_Done_Glyph( glyph );

Fail_Face:
  TT_Close_Face(face);

  /* note that in case of error (e.g. out of memory), the face stays */
  /* on the sleeping list                                            */
  return -1;
}

/****************************************************************************/
/*                                                                          */
/* Done_FontFile :                                                          */
/*                                                                          */
/*   destroys a given font file object. This will also destroy all of its   */
/*   live child font sizes (which in turn will destroy the glyph caches).   */
/*   This is done for all faces if the file is a collection.                */
/*                                                                          */
/* WARNING : The font face must be removed from its list by the caller      */
/*           before this function is called.                                */
/*                                                                          */
static  void  Done_FontFile( PFontFile  *file )
{
  static PListElement  element;
  static PListElement  next;
         ULONG         i;

#if 0    /* this part isn't really used and maybe it never will */
  /* destroy its font sizes */
  element = (*face)->sizes.head;
  while (element)
  {
    next = element->next;
    /* XXX : right now, we simply free the font size object, */
    /*       because the instance is destroyed automatically */
    /*       by FreeType.                                    */

    FREE( element->data );
    /* Done_FontSize( (PFontSize)element->data ); - later */

    Done_Element( element );
    element = next;
  }
#endif

  /* now discard the font face itself */
  if ((*file)->flags & FL_FLAG_LIVE_FACE)
  {
     for (i = 0; i < (*file)->numFaces; i++) {
        TT_Done_Glyph( (*file)->faces[i].glyph );
        TT_Close_Face( (*file)->faces[i].face );

        if ((*file)->faces[i].widths)
           FREE((*file)->faces[i].widths);
        if ((*file)->faces[i].kernIndices)
           FREE((*file)->faces[i].kernIndices);
     }
  }

  FREE( (*file)->faces );
  FREE( *file );
}


/****************************************************************************/
/*                                                                          */
/* New_FontFile :                                                           */
/*                                                                          */
/*   return the address of the TFontFile corresponding to a given           */
/*   HFF. Note that in our implementation, we could simply to a             */
/*   typecast like '(PFontFile)hff'. However, for safety reasons, we        */
/*   look up the handle in the list.                                        */
/*                                                                          */
static  PFontFile  New_FontFile( char*  file_name )
{
   static PListElement  element;
   static PFontFile     cur_file;
   static TT_CharMap    cmap;

   /* first, check if it's already open - in the live list */
   for ( element = liveFiles.head; element; element = element->next )
   {
     cur_file = (PFontFile)element->data;
     if (strcmp( cur_file->filename, file_name ) == 0)
       goto Exit_Same;
   }

   /* check in the idle list */
   for ( element = idleFiles.head; element; element = element->next )
   {
     cur_file = (PFontFile)element->data;
     if (strcmp( cur_file->filename, file_name ) == 0)
       goto Exit_Same;
   }

   /* OK, this file isn't opened yet. Create a new font face object     */
   /* then try to wake it up. This will fail if the file can't be found */
   /* or if we lack memory..                                            */

   element = New_Element();
   if (!element)
     ERRRET(NULL);

   if ( ALLOC( cur_file, sizeof(TFontFile) ) )
     ERET1( Fail_Element );

   element->data        = cur_file;
   element->key         = (long)cur_file;         /* use the HFF as cur key */

   cur_file->element    = element;
   cur_file->ref_count  = 1;
   cur_file->hff        = (HFF)cur_file;
   strcpy( cur_file->filename, file_name);
   cur_file->flags      = 0;
   cur_file->faces      = NULL;
#if 0  /* not used */
   cur_face->sizes.head = NULL;
   cur_face->sizes.tail = NULL;
   cur_face->sizes.count= 0;
#endif

   /* add new font face to sleep list */
   if (List_Insert( &idleFiles, element ))
     ERET1( Fail_File );

   /* Make enough room in the live list */
   if ( liveFiles.count >= max_open_files)
   {
     COPY( "rolling...\n" ); WRITE;
     if (Sleep_FontFile( (PFontFile)(liveFiles.tail->data) ))
       ERET1( Fail_File );
   }

   /* wake new font file */
   if ( Wake_FontFile( cur_file ) )
   {
     COPY( "could not open/wake " ); CAT( file_name ); CAT( "\r\n" ); WRITE;
     if (List_Remove( &idleFiles, element ))
       ERET1( Fail_File );

     ERET1( Fail_File );
   }

   return cur_file;      /* everything is in order */

Fail_File:
   FREE( cur_file );

Fail_Element:
   Done_Element( element );
   return  NULL;

Exit_Same:
   cur_file->ref_count++;  /* increment reference count */

   COPY( " -> (duplicate) hff = " ); CATI( cur_file->hff );
   CAT( "\r\n" ); WRITE;

   return cur_file;        /* no sense going on */
}

/****************************************************************************/
/*                                                                          */
/* getFontFile :                                                            */
/*                                                                          */
/*   return the address of the TFontFile corresponding to a given           */
/*   HFF. If asleep, the file and its face object(s) is awoken.             */
/*                                                                          */
PFontFile  getFontFile( HFF  hff )
{
  static PListElement  element;

  /* look in the live list first */
  element = List_Find( &liveFiles, (long)hff );
  if (element)
  {
    /* move it to the front of the live list - if it isn't already */
    if ( liveFiles.head != element )
    {
      if ( List_Remove( &liveFiles, element ) )
        ERRRET( NULL );

      if ( List_Insert( &liveFiles, element ) )
        ERRRET( NULL );
    }
    return (PFontFile)(element->data);
  }

  /* the file may be asleep, look in the second list */
  element = List_Find( &idleFiles, (long)hff );
  if (element)
  {
    /* we need to awake the font, but before that, we must be sure */
    /* that there is enough room in the live list                  */
    if ( liveFiles.count >= max_open_files )
      if (Sleep_FontFile( (PFontFile)(liveFiles.tail->data) ))
        ERRRET( NULL );

    if ( Wake_FontFile( (PFontFile)(element->data) ) )
      ERRRET( NULL );

    COPY ( "hff " ); CATI( hff ); CAT( " awoken\n" ); WRITE;
    return (PFontFile)(element->data);
  }

  COPY( "Could not find hff " ); CATI( hff ); CAT( " in lists\n" ); WRITE;

#ifdef DEBUG

  /* dump files lists */
  COPY( "Live files : " ); CATI( liveFiles.count ); CAT( "\r\n" ); WRITE;

  for (element = liveFiles.head; element; element = element->next)
  {
    COPY( ((PFontFile)(element->data))->filename ); CAT("\r\n");WRITE;
  }

  COPY( "Idle files : " ); CATI( idleFiles.count ); CAT( "\r\n" ); WRITE;
  for (element = idleFiles.head; element; element = element->next)
  {
    COPY( ((PFontFile)(element->data))->filename ); CAT("\r\n");WRITE;
  }
#endif

  /* could not find the HFF in the list */
  return NULL;
}


/****************************************************************************/
/*                                                                          */
/* getFontSize :                                                            */
/*                                                                          */
/*   return pointer to a TFontSize given a HFC handle, NULL if error        */
/*                                                                          */
static  PFontSize  getFontSize( HFC  hfc )
{
   int i;
   for ( i = 0; i < MAX_CONTEXTS; i++ )
      if ( contexts[i].hfc == hfc ) {
         return &contexts[i];
      }

   return NULL;
}

#ifdef USE_UCONV

/* maximum number of cached UCONV objects */
#define MAX_UCONV_CACHE   10

/* UCONV object used for conversion from UGL to Unicode */
#define UCONV_TYPE_UGL    1

/* UCONV objects used for conversion from local DBCS codepage to Unicode */
#define UCONV_TYPE_BIG5   2
#define UCONV_TYPE_SJIS   4

/* UCONV objects cache entry */
typedef struct  _UCACHEENTRY {
   UconvObject   object;      /* actual UCONV object */
   PID           pid;         /* process ID the object is valid for */
   ULONG         type;        /* type of UCONV object (UGL or DBCS) */
} UCACHEENTRY, *PUCACHEENTRY;

/* UCONV globals */
static UCACHEENTRY    UconvCache[MAX_UCONV_CACHE];  /* 10 should do it */
static int            slotsUsed = 0;     /* number of cache slots used */

/****************************************************************************/
/*                                                                          */
/* getUconvObject :                                                         */
/*                                                                          */
/*   a function to cache UCONV objects based on current process. The only   */
/*  problem is that FT/2 currently doesn't keep track of processes and      */
/*  consequently the objects aren't freed when a process ends. But UCONV    */
/*  frees the objects itself anyway.                                        */
int getUconvObject(UniChar *name, UconvObject *ConvObj, ULONG UconvType) {
   PPIB                  ppib;   /* process/thread info blocks */
   PTIB                  ptib;
   PID                   curPid; /* current process ID */
   int                   i;

   /* query current process ID */
   if (DosGetInfoBlocks(&ptib, &ppib))
      return -1;

   curPid = ppib->pib_ulpid;

   if (slotsUsed == 0) {     /* initialize cache */
      if (UniCreateUconvObject(name, ConvObj) != ULS_SUCCESS)
         return -1;
      UconvCache[0].object = *ConvObj;
      UconvCache[0].pid    = curPid;
      UconvCache[0].type   = UconvType;

      for (i = 1; i < MAX_UCONV_CACHE; i++) {
         UconvCache[i].object = NULL;
         UconvCache[i].pid    = 0;
      }
      slotsUsed = 1;
      return 0;
   }

   /* search cache for available conversion object */
   i = 0;
   while ((UconvCache[i].pid != curPid || UconvCache[i].type != UconvType)
          && i < slotsUsed)
      i++;

   if (i < slotsUsed) {  /* entry found in cache */
      *ConvObj = UconvCache[i].object;
      return 0;
   }

   /* if cache is full, remove first entry and shift the others 'down' */
   if (slotsUsed == MAX_UCONV_CACHE) {
      UniFreeUconvObject(UconvCache[0].object);
      for (i = 1; i < MAX_UCONV_CACHE; i++) {
         UconvCache[i - 1].object = UconvCache[i].object;
         UconvCache[i - 1].pid    = UconvCache[i].pid;
         UconvCache[i - 1].type   = UconvCache[i].type;
      }
   }

   if (UniCreateUconvObject(name, ConvObj) != ULS_SUCCESS)
      return -1;

   if (slotsUsed < MAX_UCONV_CACHE)
      slotsUsed++;

   UconvCache[slotsUsed - 1].object = *ConvObj;
   UconvCache[slotsUsed - 1].pid    = curPid;
   UconvCache[slotsUsed - 1].type   = UconvType;

   return 0;
}

/****************************************************************************/
/*                                                                          */
/* CleanUCONVCache :                                                        */
/*                                                                          */
/*  When process is terminated, removes this process' entries in the UCONV  */
/* object cache. Errors are disregarded at this point.                      */
void CleanUCONVCache(void) {
   PPIB                  ppib;   /* process/thread info blocks */
   PTIB                  ptib;
   PID                   curPid; /* current process ID */
   int                   i = 0, j;

   /* query current process ID */
   if (DosGetInfoBlocks(&ptib, &ppib))
      return;

   curPid = ppib->pib_ulpid;

   while (i < slotsUsed) {
      /* if PID matches, remove the entry and shift the others 'down' (or up?) */
      if (UconvCache[i].pid == curPid) {
         UniFreeUconvObject(UconvCache[i].object);
         for (j = i + 1; j < slotsUsed; j++) {
            UconvCache[j - 1].object = UconvCache[j].object;
            UconvCache[j - 1].pid    = UconvCache[j].pid;
            UconvCache[j - 1].type   = UconvCache[j].type;
         }
         slotsUsed--;
      }
      i++;
   }
}
#endif  /* USE_UCONV */

/****************************************************************************/
/*                                                                          */
/* PM2TT :                                                                  */
/*                                                                          */
/*   a function to convert PM codepoint to TT glyph index. This is the real */
/*   tricky part.                                                           */
/*    mode = TRANSLATE_UGL - translate UGL to Unicode                       */
/*    mode = TRANSLATE_SYMBOL - no translation - symbol font                */
/*    mode = TRANSLATE_UNICODE- no translation - Unicode                    */
static  int PM2TT( TT_CharMap  charMap,
                   ULONG       mode,
                   int         index)
{
#ifdef USE_UCONV
   /* Brand new version that uses UCONV.DLL. This should make FreeType/2 */
   /* smaller and at the same time more flexible as it now should use    */
   /* the Unicode translation tables supplied with base OS/2 Warp 4.     */
   /* Unfortunately there's a complication (again) since UCONV objects   */
   /* created in one process can't be used in another. Therefore we      */
   /* keep a small cache of recently used UCONV objects.                 */
   static UconvObject   UGLObj = NULL; /* UGL->Unicode conversion object */
   static BOOL          UconvSet         = FALSE;
          char          char_data[2], *pin_char_str;
          size_t        in_bytes_left, uni_chars_left, num_subs;
          UniChar       *pout_uni_str, uni_buffer[4];
          int           rc;
   static UniChar       uglName[10] = L"OS2UGL";
   static UniChar       uglNameBig5[10] = L"IBM-950";
   static UniChar       uglNameSJIS[10] = L"IBM-943";

   switch (mode) {
      case TRANSLATE_UGL:
         if (UconvSet == FALSE) {
            switch (iLangId) {   /* select proper conversion table */
               case TT_MS_LANGID_GREEK_GREECE:
                  strncpy((char*)uglName, (char*)L"OS2UGLG", 16);
                  break;
               case TT_MS_LANGID_HEBREW_ISRAEL:
                  strncpy((char*)uglName, (char*)L"OS2UGLH", 16);
                  break;
               case TT_MS_LANGID_ARABIC_SAUDI_ARABIA:
                  strncpy((char*)uglName, (char*)L"OS2UGLA", 16);
                  break;
            }
            UconvSet = TRUE;
         }

         /* get Uconv object - either new or cached */
         if (getUconvObject(uglName, &UGLObj, UCONV_TYPE_UGL) != 0)
            return 0;

         if (index > MAX_GLYPH)
            return 0;

         char_data[0] = index;
         char_data[1] = index >> 8;

         pout_uni_str = uni_buffer;
         pin_char_str = char_data;
         in_bytes_left = 2;
         uni_chars_left = 1;

         rc = UniUconvToUcs(UGLObj, (void**)&pin_char_str, &in_bytes_left,
                           &pout_uni_str, &uni_chars_left,
                           &num_subs);
         if (rc != ULS_SUCCESS)
            return 0;
         else
            return TT_Char_Index(charMap, ((unsigned short*)uni_buffer)[0]);

      case TRANSLATE_SYMBOL:
      case TRANSLATE_UNICODE:
      case TRANSLATE_BIG5:
      case TRANSLATE_SJIS:
         return TT_Char_Index(charMap, index);

      case TRANSLATE_UNI_BIG5:
      case TRANSLATE_UNI_SJIS:

         /* get Uconv object - either new or cached */
         switch (mode) {
            /* get proper conversion object */
            case TRANSLATE_UNI_BIG5:
               if (getUconvObject(uglNameBig5, &UGLObj, UCONV_TYPE_BIG5) != 0)
                  return 0;
               break;

            case TRANSLATE_UNI_SJIS:
               if (getUconvObject(uglNameSJIS, &UGLObj, UCONV_TYPE_SJIS) != 0)
                  return 0;
               break;
         }

         /* Note the bytes are swapped here for double byte chars! */
         if (index & 0xFF00) {
            char_data[0] = (index & 0xFF00) >> 8;
            char_data[1] = index & 0x00FF;
         }
         else {
            char_data[0] = index;
            char_data[1] = 0;
         }

         pout_uni_str = uni_buffer;
         pin_char_str = char_data;
         in_bytes_left = 2;
         uni_chars_left = 2;

         rc = UniUconvToUcs(UGLObj, (void**)&pin_char_str, &in_bytes_left,
                           &pout_uni_str, &uni_chars_left,
                           &num_subs);
         if (rc != ULS_SUCCESS)
            return 0;
         else
            return TT_Char_Index(charMap, ((unsigned short*)uni_buffer)[0]);

      default:
         return 0;
   }
#else
   switch (mode)
   {
      /* convert from PM383 to Unicode */
      case TRANSLATE_UGL:
         /* TODO: Hebrew and Arabic UGL */
         if (iLangId == TT_MS_LANGID_GREEK_GREECE)  /* use Greek UGL */
            if ((index >= GREEK_START) && (index < GREEK_START + GREEK_GLYPHS))
               return TT_Char_Index(charMap, SubUGLGreek[index - GREEK_START]);

         if (index <= MAX_GLYPH)
            return TT_Char_Index(charMap, UGL2Uni[index]);
         else
            ERRRET(0);

      case TRANSLATE_SYMBOL :
      case TRANSLATE_UNICODE:
      case TRANSLATE_BIG5:
      case TRANSLATE_SJIS:
         return TT_Char_Index(charMap, index);

      default:
         return 0;
   }
#endif
}

/****************************************************************************/
/*                                                                          */
/* mystricmp :                                                              */
/*                                                                          */
/* A simple function for comparing strings without case sensitivity. Just   */
/* returns zero if strings match, one otherwise. I wrote this because       */
/* stricmp is not available in the subsystem run-time library (probably     */
/* because it uses locales). toupper() is unfortunately unavailable too.    */
/*                                                                          */

#define toupper( c ) ( ((c) >= 'a') && ((c) <= 'z') ? (c) - 'a' + 'A' : (c) )

static
int mystricmp(const char *s1, const char *s2) {
   int i = 0;
   int match = 0;
   int len = strlen(s1);

   if (len != strlen(s2))
      return 1;   /* no match */

   while (i < len) {
      if (toupper(s1[i]) != toupper(s2[i])) {
         match = 1;
         break;
      }
      i++;
   }
   return match;
}

/* DBCS enabled strrchr (only looks for SBCS chars though) */
static
char *mystrrchr(char *s, char c) {
   int i = 0;
   int lastfound = -1;
   int len = strlen(s);

   while (i <= len) {
      if (IsDBCSChar(s[i])) {
         i += 2;
         continue;
      }
      if (s[i] == c)
         lastfound = i;
      i++;
   }
   if (lastfound == -1)
      return NULL;
   else
      return s + lastfound;
}

/* -------------------------------------------------------------------------*/
/* here begin the exported functions                                        */
/* -------------------------------------------------------------------------*/

/****************************************************************************/
/*                                                                          */
/* ConvertFontFile :                                                        */
/*                                                                          */
/*  Install/delete font file                                                */
/*                                                                          */
LONG _System ConvertFontFile( PSZ  source,
                              PSZ  dest_dir,
                              PSZ  new_name )
{
   PSZ  source_name;

   COPY("ConvertFontFile: Src = "); CAT(source);
   if (dest_dir) {
      CAT(", DestDir = "); CAT(dest_dir);
   }
   CAT("\r\n"); WRITE;

   if (dest_dir && new_name)
   {
     /* install the font file */
     source_name = mystrrchr( source, '\\' );  /* find the last backslash */
     if (!source_name)
       ERRRET(-1);

     source_name++;
     strcpy( new_name, source_name );

     /* check if file is to be copied onto itself */
     if (strncmp(source, dest_dir, strlen(dest_dir)) == 0)
        return OK;  /* do nothing */

     if ( DosCopy( source, dest_dir, DCPY_EXISTING) )  /* overwrite file */
       ERRRET(-1);  /* XXX : we should probably set the error condition */

      COPY(" -> Name: "); CAT(new_name); CAT("\r\n"); WRITE;
   }
   else
   {
      COPY("Delete file "); CAT(source); CAT("\r\n"); WRITE;
      DosDelete(source);  /* fail quietly */
   }

   return OK;
}

/****************************************************************************/
/*                                                                          */
/* LoadFontFile :                                                           */
/*                                                                          */
/*  open a font file and return a handle for it                             */
/*                                                                          */
HFF _System LoadFontFile( PSZ file_name )
{
   PSZ           extension;
   PFontFile     cur_file;
   PListElement  element;

   COPY( "LoadFontFile " ); CAT( file_name ); CAT( "\r\n" ); WRITE;

   /* first check if the file extension is supported */
   extension = mystrrchr( file_name, '.' );  /* find the last dot */
   if ( extension == NULL ||
        (mystricmp(extension, ".TTF") &&
         mystricmp(extension, ".TTC")) )
     return ((HFF)-1);

   /* now actually open the file */
   cur_file = New_FontFile( file_name );
   if (cur_file)
     return  cur_file->hff;
   else
     return (HFF)-1;
}

/****************************************************************************/
/*                                                                          */
/* UnloadFontFile :                                                         */
/*                                                                          */
/*  destroy resources associated with a given HFF                           */
/*                                                                          */
LONG _System UnloadFontFile( HFF hff )
{
   PListElement  element;

   COPY("UnloadFontFile: hff = "); CATI((int) hff); CAT("\r\n"); WRITE;

   /* look in the live list first */
   for (element = liveFiles.head; element; element = element->next)
   {
     if (element->key == (long)hff)
     {
       PFontFile  file = (PFontFile)element->data;

       if (--file->ref_count > 0)  /* don't really close, return OK */
         return 0;

       List_Remove( &liveFiles, element );
       Done_Element( element );
       Done_FontFile( &file );
       return 0;
     }
   }

   /* now look in sleep list */
   for (element = idleFiles.head; element; element = element->next)
   {
     if (element->key == (long)hff)
     {
       PFontFile  file = (PFontFile)element->data;

       if (--file->ref_count > 0)  /* don't really close, return OK */
         return 0;

       List_Remove( &idleFiles, element );
       Done_Element( element );
       Done_FontFile( &file );
       return 0;
     }
   }

   /* didn't find the file */
   return -1;
}

/****************************************************************************/
/*                                                                          */
/* QueryFaces :                                                             */
/*                                                                          */
/*   Return font metrics. This routine has to do a lot of not very          */
/*   hard work.                                                             */
/*                                                                          */
LONG _System QueryFaces( HFF          hff,
                         PIFIMETRICS  pifiMetrics,
                         ULONG        cMetricLen,
                         ULONG        cFontCount,
                         ULONG        cStart)
{
   static TT_Face_Properties   properties;
   static IFIMETRICS           ifi;   /* temporary structure */
          PFontFace            pface;
          TT_Header            *phead;
          TT_Horizontal_Header *phhea;
          TT_OS2               *pOS2;
          TT_Postscript        *ppost;
          PIFIMETRICS          pifi2;
          PFontFile            file;
          LONG                 index, faceIndex, ifiCount = 0;
          char                 *name;

   COPY( "QueryFaces: hff = " ); CATI( hff );
   CAT(  ", cFontCount = " );    CATI( cFontCount );
   CAT(  ", cStart = " );        CATI( cStart );
   CAT(  ", cMetricLen = " );    CATI( cMetricLen );
   CAT( "\r\n");
   WRITE;

   file = getFontFile(hff);
   if (!file)
      ERRRET(-1) /* error, invalid handle */

   if (cMetricLen == 0) {   /* only number of faces is requested */
      #ifdef  FAKE_TNR
      /* create an alias for Times New Roman */
      pface = &(file->faces[0]);
      name = LookupName(pface->face, TT_NAME_ID_FONT_FAMILY);
      if (!strcmp(name, "Times New Roman")) {
         file->flags |= FL_FLAG_FAKE_ROMAN;
         return 2;
      }
      #endif
      if (file->flags & FL_FLAG_DBCS_FILE)
         return file->numFaces * 2;
      else
         return file->numFaces;
   }

   for (faceIndex = 0; faceIndex < file->numFaces; faceIndex++) {
      /* get pointer to this face's data */
      pface = &(file->faces[faceIndex]);

      TT_Get_Face_Properties( pface->face, &properties );

      pOS2  = properties.os2;
      phead = properties.header;
      phhea = properties.horizontal;
      ppost = properties.postscript;

      /* get font name and check it's really found */
      name = LookupName(pface->face, TT_NAME_ID_FONT_FAMILY);
      if (name == NULL)
         ERET1(Fail);

      strncpy(ifi.szFamilyname, name, FACESIZE);
      ifi.szFamilyname[FACESIZE - 1] = '\0';

      name = LookupName(pface->face, TT_NAME_ID_FULL_NAME);
      if (name == NULL) {
         ERET1(Fail);
      }
      strncpy(ifi.szFacename, name, FACESIZE);
      ifi.szFacename[FACESIZE - 1] = '\0';

      /* If Unicode cmap exists in font and it contains more than 1024 glyphs,   */
      /* then do not translate from UGL to Unicode and use straight Unicode.     */
      /* But first check if it's a DBCS font and handle it properly              */
      if ((pface->charMode == TRANSLATE_UGL) && (properties.num_Glyphs > 1024))
      {
         LONG  specEnc;
         BOOL  UDCflag = FALSE;   /* !!!!TODO: UDC support */

         specEnc = interfaceSEId(pface->face, UDCflag, PSEID_UNICODE);
         switch (specEnc) {
            case PSEID_SHIFTJIS:
               strcpy( ifi.szGlyphlistName, "PMJPN" );
               pface->charMode = TRANSLATE_UNI_SJIS;
               break;

            case PSEID_BIG5:
               strcpy( ifi.szGlyphlistName, "PMCHT" );
               pface->charMode = TRANSLATE_UNI_BIG5;
               break;

            default:  /* do use straight Unicode */
               strcpy( ifi.szGlyphlistName, "UNICODE" );
               pface->charMode = TRANSLATE_UNICODE; /* straight Unicode */
         }
#if 0
         strcpy( ifi.szGlyphlistName, "PMJPN" );
         pface->charMode = TRANSLATE_UNI_SJIS;
#endif
      }
      else
         if (pface->charMode == TRANSLATE_SYMBOL)  /* symbol encoding    */
            strcpy(ifi.szGlyphlistName, "SYMBOL");
      else
         if (pface->charMode == TRANSLATE_BIG5)    /* Big5 encoding      */
            strcpy(ifi.szGlyphlistName, "PMCHT");
      else
         if (pface->charMode == TRANSLATE_SJIS)
            strcpy(ifi.szGlyphlistName, "PMJPN");  /* ShiftJIS encoding  */
      else
         strcpy(ifi.szGlyphlistName, "PM383");

      ifi.idRegistry         = 0;
      ifi.lCapEmHeight       = phead->Units_Per_EM; /* ??? probably correct  */
      ifi.lXHeight           = phead->yMax /2;      /* IBM TRUETYPE.DLL does */
      ifi.lMaxAscender       = pOS2->usWinAscent;

      if ((LONG)pOS2->usWinDescent >= 0)
         ifi.lMaxDescender   = pOS2->usWinDescent;
      else
         ifi.lMaxDescender   = -pOS2->usWinDescent;

      ifi.lLowerCaseAscent   = phhea->Ascender;
      ifi.lLowerCaseDescent  = -phhea->Descender;

      ifi.lInternalLeading   = ifi.lMaxAscender + ifi.lMaxDescender
                               - ifi.lCapEmHeight;

      ifi.lExternalLeading    = 0;
      ifi.lAveCharWidth       = pOS2->xAvgCharWidth;
      ifi.lMaxCharInc         = phhea->advance_Width_Max;
      ifi.lEmInc              = phead->Units_Per_EM;
      ifi.lMaxBaselineExt     = ifi.lMaxAscender + ifi.lMaxDescender;
      ifi.fxCharSlope         = -ppost->italicAngle;    /* is this correct ?  */
      ifi.fxInlineDir         = 0;
      ifi.fxCharRot           = 0;
      ifi.usWeightClass       = pOS2->usWeightClass;    /* hopefully OK       */
      ifi.usWidthClass        = pOS2->usWidthClass;
      ifi.lEmSquareSizeX      = phead->Units_Per_EM;
      ifi.lEmSquareSizeY      = phead->Units_Per_EM;    /* probably correct   */
      ifi.giFirstChar         = 0;            /* following values should work */
      ifi.giLastChar          = 503;          /* either 383 or 503            */
      ifi.giDefaultChar       = 0;
      ifi.giBreakChar         = 32;
      ifi.usNominalPointSize  = 120;   /*    these are simply constants       */
      ifi.usMinimumPointSize  = 10;
      ifi.usMaximumPointSize  = 10000; /* limit to 1000 pt (like the ATM fonts) */
      ifi.fsType              = pOS2->fsType & IFIMETRICS_LICENSED; /* ???    */
      ifi.fsDefn              = IFIMETRICS_OUTLINE;  /* always with TrueType  */
      ifi.fsSelection         = 0;
      ifi.fsCapabilities      = 0; /* must be zero according to the IFI spec */
      ifi.lSubscriptXSize     = pOS2->ySubscriptXSize;
      ifi.lSubscriptYSize     = pOS2->ySubscriptYSize;
      ifi.lSubscriptXOffset   = pOS2->ySubscriptXOffset;
      ifi.lSubscriptYOffset   = pOS2->ySubscriptYOffset;
      ifi.lSuperscriptXSize   = pOS2->ySuperscriptXSize;
      ifi.lSuperscriptYSize   = pOS2->ySuperscriptYSize;
      ifi.lSuperscriptXOffset = pOS2->ySuperscriptXOffset;
      ifi.lSuperscriptYOffset = pOS2->ySuperscriptYOffset;
      ifi.lUnderscoreSize     = ppost->underlineThickness;
      if (ifi.lUnderscoreSize == 150)
         ifi.lUnderscoreSize = 100;  /* little fix for Arial */
      ifi.lUnderscorePosition = -ppost->underlinePosition;
      ifi.lStrikeoutSize      = pOS2->yStrikeoutSize;
      ifi.lStrikeoutPosition  = pOS2->yStrikeoutPosition;

#if 1
      if (pface->directory.nTables != 0 &&
          pface->directory.tables[0].format == 0) { /* we support only format */
         ifi.cKerningPairs   = (pface->directory.tables[0].length - 8) / 6;
         ifi.fsType |= IFIMETRICS_KERNING; /* !!! for testing only! */
      }
      else
#endif
         ifi.cKerningPairs   = 0;

      /* Note that the following field seems to be the only reliable method of */
      /* recognizing a TT font from an app!  Not that it should be done.       */
      ifi.ulFontClass        = 0x10D; /* just like TRUETYPE.DLL */

      /* the following adjustment are needed because the TT spec defines */
      /* usWeightClass and fsType differently                            */
      if (ifi.usWeightClass >= 100)
         ifi.usWeightClass /= 100;
      if (ifi.usWeightClass == 4)
         ifi.usWeightClass = 5;    /* does this help? */
      if (pOS2->panose[3] == 9) {
         ifi.fsType |= IFIMETRICS_FIXED;
         pface->flags |= FC_FLAG_FIXED_WIDTH; /* we'll need this later */
      }

      switch (pface->charMode) {      /* adjustments for var. encodings */
         case TRANSLATE_UNICODE:
            ifi.giLastChar = pOS2->usLastCharIndex;
            ifi.fsType |= IFIMETRICS_MBCS | IFIMETRICS_DBCS;
            break;

         case TRANSLATE_SYMBOL:
            ifi.giLastChar = 255;
            break;

         case TRANSLATE_BIG5:
         case TRANSLATE_UNI_BIG5:
            ifi.giLastChar = 383;
            ifi.fsType |= IFIMETRICS_MBCS | IFIMETRICS_DBCS;
            break;

         case TRANSLATE_SJIS:
         case TRANSLATE_UNI_SJIS:
            ifi.giLastChar = 890;
            ifi.fsType |= IFIMETRICS_MBCS | IFIMETRICS_DBCS;
            break;

      }

      /* adjust fsSelection (TT defines this differently) */
      /* Note: Interestingly, the PMATM font driver seems to use the values
          defined in TT spec, at least for italic. Strange. Better leave it. */
      if (pOS2->fsSelection & 0x01) {
          ifi.fsSelection |= 0x01;
      }
      if (pOS2->fsSelection & 0x02) {
          ifi.fsSelection |= IFIMETRICS_UNDERSCORE;
      }
      if (pOS2->fsSelection & 0x04) {
          ifi.fsSelection |= IFIMETRICS_OVERSTRUCK;
      }

      /* copy the right amount of data to output buffer,         */
      /* also handle the 'fake' vertically rendered DBCS fonts   */
      index = faceIndex * ((file->flags & FL_FLAG_DBCS_FILE) ? 2 : 1);
         if ((index >= cStart) && (index < (cStart + cFontCount))) {
         memcpy((((PBYTE) pifiMetrics) + ifiCount), &ifi,
            sizeof(IFIMETRICS) > cMetricLen ? cMetricLen : sizeof(IFIMETRICS));
         ifiCount += cMetricLen;
      }
      if ((file->flags & FL_FLAG_DBCS_FILE) && (index + 1 >= cStart) &&
          (index + 1 < (cStart + cFontCount))) {

         pifi2 = (PIFIMETRICS) (((PBYTE) pifiMetrics) + ifiCount);
         memcpy(pifi2, &ifi,
                sizeof(IFIMETRICS) > cMetricLen ? cMetricLen : sizeof(IFIMETRICS));
         strcpy(pifi2->szFamilyname + 1, ifi.szFamilyname);
         pifi2->szFamilyname[0] = '@';
         strcpy(pifi2->szFacename + 1, ifi.szFacename);
         pifi2->szFacename[0] = '@';
         ifiCount += cMetricLen;
      }
      #ifdef  FAKE_TNR
      if ((file->flags & FL_FLAG_FAKE_ROMAN) && (index + 1 >= cStart) &&
          (index + 1 < (cStart + cFontCount))) {
         pifi2 = (PIFIMETRICS) (((PBYTE) pifiMetrics) + ifiCount);
         memcpy(pifi2, &ifi,
                sizeof(IFIMETRICS) > cMetricLen ? cMetricLen : sizeof(IFIMETRICS));
         strcpy(pifi2->szFamilyname, "Roman");
         switch (strlen(ifi.szFacename)) {  /* This looks weird but... works */
            case 15: /* Times New Roman */
               strcpy(pifi2->szFacename, "Tms Rmn");
               break;
            case 20: /* Times New Roman Bold*/
               strcpy(pifi2->szFacename, "Tms Rmn Bold");
               break;
            case 22: /* Times New Roman Italic*/
               strcpy(pifi2->szFacename, "Tms Rmn Italic");
               break;
            case 27: /* Times New Roman Bold Italic*/
               strcpy(pifi2->szFacename, "Tms Rmn Bold Italic");
               break;
         }
         ifiCount += cMetricLen;
      }
      #endif
   }

Exit:
   TT_Flush_Face(pface->face);
   return cFontCount;

Fail:
   TT_Flush_Face(pface->face);
   return -1;
}

/****************************************************************************/
/*                                                                          */
/* OpenFontContext :                                                        */
/*                                                                          */
/*  open new font context                                                   */
/*                                                                          */
HFC _System OpenFontContext( HFF    hff,
                             ULONG  ulFont)
{
          int          i = 0;
   static TT_Instance  instance;
   static PFontFile    file;
          ULONG        faceIndex;

   COPY("OpenFontContext: hff = "); CATI((int) hff); CAT("\r\n");
   COPY("              ulFont = "); CATI((int) ulFont); CAT("\r\n");
   WRITE;

   file = getFontFile(hff);
   if (!file)
      ERRRET((HFC)-1) /* error, invalid font handle */

   /* calculate real face index in font file */
   faceIndex = file->flags & FL_FLAG_DBCS_FILE ? ulFont / 2 : ulFont;

   #ifdef  FAKE_TNR
   if (file->flags & FL_FLAG_FAKE_ROMAN)
      /* This font isn't real! */
      faceIndex = 0;
   #endif

   if (faceIndex > file->numFaces)
      ERRRET((HFC)-1)

   /* OK, create new instance with defaults */
   error = TT_New_Instance( file->faces[faceIndex].face, &instance);
   if (error)
     ERET1( Fail );

   /* Instance resolution is set to 72 dpi and is never changed     */
   error = TT_Set_Instance_Resolutions(instance, 72, 72);
   if (error)
      ERRRET((HFC)-1)

   /* find first unused index */
   i = 0;
   while ((contexts[i].hfc != 0) && (i < MAX_CONTEXTS))
      i++;

   if (i == MAX_CONTEXTS)
     ERET1( Fail );  /* no free slot in table */

   contexts[i].hfc          = (HFC)(i + 0x100); /* initialize table entries */
   contexts[i].instance     = instance;
   contexts[i].transformed  = FALSE;            /* no scaling/rotation assumed */
   contexts[i].file         = file;
   contexts[i].faceIndex    = faceIndex;

   /* for DBCS fonts/collections, odd indices are vertical versions*/
   if ((file->flags & FL_FLAG_DBCS_FILE) && (ulFont & 1))
      contexts[i].vertical  = TRUE;
   else
      contexts[i].vertical  = FALSE;

   file->flags |= FL_FLAG_CONTEXT_OPEN;         /* flag as in-use */

   COPY("-> hfc "); CATI((int) contexts[i].hfc); CAT("\r\n"); WRITE;

   TT_Flush_Face(file->faces[faceIndex].face);
   return contexts[i].hfc; /* everything OK */

Fail:
   TT_Flush_Face(file->faces[faceIndex].face);
   return (HFC)-1;
}

/****************************************************************************/
/*                                                                          */
/* SetFontContext :                                                         */
/*                                                                          */
/*  set font context parameters                                             */
/*                                                                          */
LONG _System SetFontContext( HFC           hfc,
                             PCONTEXTINFO  pci )
{
   LONG       ptsize, temp, emsize;
   PFontSize  size;

   COPY("SetFontContext: hfc = ");           CATI((int) hfc);
   CAT(", sizlPPM.cx = ");                   CATI((int) pci->sizlPPM.cx);
   CAT(", sizlPPM.cy = ");                   CATI((int) pci->sizlPPM.cy);
   CAT("\r\n                pfxSpot.x = ");  CATI((int) pci->pfxSpot.x);
   CAT(", pfxSpot.y = ");                    CATI((int) pci->pfxSpot.y);
   CAT("\r\n                eM11 = ");       CATI((int) pci->matXform.eM11);
   CAT(", eM12 = ");                         CATI((int) pci->matXform.eM12);
   CAT(", eM21 = ");                         CATI((int) pci->matXform.eM21);
   CAT(", eM22 = ");                         CATI((int) pci->matXform.eM22);
   CAT("\r\n");
   WRITE;

   size = getFontSize(hfc);
   if (!size)
      ERRRET(-1) /* error, invalid context handle */

   emsize = size->file->faces[size->faceIndex].em_size;

   /* Look at matrix and see if a transform is asked for */
   /* Actually when rotating by 90 degrees hinting could be used */

   size->transformed =
     ( pci->matXform.eM11 != pci->matXform.eM22       ||
      (pci->matXform.eM12 | pci->matXform.eM21) != 0  ||
       pci->matXform.eM11 <= 0 );

   if ( size->transformed )
   {
      /* check for simple stretch in one direction */
      if ((pci->matXform.eM11 > 0 && pci->matXform.eM22 > 0) &&
          (pci->matXform.eM12 | pci->matXform.eM21) == 0) {

         LONG    ptsizex, ptsizey;

         size->transformed = FALSE; /* will be handled like nontransformed font */

         ptsizex = (emsize * pci->matXform.eM11) >> 10;
         ptsizey = (emsize * pci->matXform.eM22) >> 10;

         error = TT_Set_Instance_CharSizes(size->instance, ptsizex, ptsizey);
         if (error)
            ERRRET(-1)  /* engine problem */

         return 0;
      }
      /* note that eM21 and eM12 are swapped; I have no idea why, but */
      /* it seems to be correct */
      size->matrix.xx = pci->matXform.eM11 * 64;
      size->matrix.xy = pci->matXform.eM21 * 64;
      size->matrix.yx = pci->matXform.eM12 * 64;
      size->matrix.yy = pci->matXform.eM22 * 64;

      /* set pointsize to Em size; this effectively disables scaling */
      /* but enables use of hinting */
      error = TT_Set_Instance_CharSize(size->instance, emsize);
      if (error)
         ERRRET(-1)  /* engine problem */

      return 0;
   }

   /* calculate & set  point size  */
   ptsize = (emsize * (pci->matXform.eM11 + pci->matXform.eM21)) >> 10;

   if (ptsize <= 0)                /* must not allow zero point size ! */
      ptsize = 1;                  /* !!!  should be handled better     */

   error = TT_Set_Instance_CharSize(size->instance, ptsize);
   if (error)
      ERRRET(-1)  /* engine problem */

   return 0;      /* pretend everything is OK */
}

/****************************************************************************/
/*                                                                          */
/* CloseFontContext :                                                       */
/*                                                                          */
/*  destroy a font context                                                  */
/*                                                                          */
LONG _System CloseFontContext( HFC hfc)
{
   PFontSize  size;

   COPY("CloseFontContext: hfc = "); CATI((int)hfc); CAT("\r\n"); WRITE;

   size = getFontSize(hfc);
   if (!size)
      ERRRET(-1) /* error, invalid context handle */

   /* mark table entry as free */
   size->hfc = 0;

   /* !!!!! set flag in TFontFile structure */
   size->file->flags &= ~FL_FLAG_CONTEXT_OPEN;   /* reset the in-use flag */

   if (size->file->flags & FL_FLAG_LIVE_FACE) {
      COPY("Closing instance: "); CATI((int)(size->instance.z)); CAT("\r\n"); WRITE;
      error = TT_Done_Instance(size->instance);
      if (error)
         ERRRET(-1)  /* engine error */
   }

   COPY("CloseFontContext successful\r\n"); WRITE;

   return 0; /* success */
}

#define MAX_KERN_INDEX  504

GLYPH ReverseTranslate(PFontFace face, USHORT index) {
   ULONG  i;
   GLYPH  newidx = 0;

   /* TODO: enable larger fonts */
   for (i = 0; i < MAX_KERN_INDEX; i++) {
      newidx = PM2TT(face->charMap,
                     face->charMode,
                     i);
      if (newidx == index)
         break;
   }
   if (i < MAX_KERN_INDEX)
      return i;
   else
      return 0;
}

/****************************************************************************/
/*                                                                          */
/* QueryFaceAttr                                                            */
/*                                                                          */
/*  Return various info about font face                                     */
/*                                                                          */
LONG _System QueryFaceAttr( HFC     hfc,
                            ULONG   iQuery,
                            PBYTE   pBuffer,
                            ULONG   cb,
                            PGLYPH  pagi,
                            GLYPH   giStart )
{
   int                        count, i = 0;
   PFontSize                  size;
   PFontFace                  face;
   static TT_Face_Properties  properties;
   TT_OS2                     *pOS2;
   ABC_TRIPLETS*              pt;

   COPY("QueryFaceAttr: hfc = "); CATI((int) hfc); CAT("\r\n"); WRITE;

   size = getFontSize(hfc);
   if (!size)
      ERRRET(-1) /* error, invalid context handle */

   face = &(size->file->faces[size->faceIndex]);

   if (iQuery == FD_QUERY_KERNINGPAIRS)
   {
      TT_Kern_0        kerntab;   /* actual kerning table */
      ULONG            used = 0;  /* # bytes used in output buffer */
      FD_KERNINGPAIRS  *kpair;
      USHORT           *kernIndices, idx;

      count = cb / sizeof(FD_KERNINGPAIRS);

      COPY("QUERY_KERNINGPAIRS, "); CATI((int) count);
      CAT("\r\n"); WRITE;
#if 1

      if (face->directory.tables == NULL)
         return 0;  /* no kerning info provided */
      /* !!!! could use better error checking */
      /* Only format 0 is supported (which is what M$ recommends) */
      if (face->directory.tables[0].format != 0) /* need only format 0 */
         ERRRET(-1);

      error = TT_Load_Kerning_Table(face->face, 0);
      if (error)
        ERET1( Fail );

      kerntab = face->directory.tables[0].t.kern0;
      kpair = (PVOID)pBuffer;

      if (face->kernIndices == NULL) {
         TT_Get_Face_Properties( face->face, &properties );
         error = ALLOC(face->kernIndices,
                       properties.num_Glyphs * sizeof (USHORT));
         if (error)
            ERET1( Fail );

         /* fill all entries with -1s */
         memset(face->kernIndices, 0xFF,
            properties.num_Glyphs * sizeof (USHORT));
      }

      kernIndices = face->kernIndices;

      while ((i < kerntab.nPairs) && (i < count))
      {
         idx = kerntab.pairs[i].left;
         if (kernIndices[idx] == (USHORT)-1)
            kernIndices[idx] = ReverseTranslate(face, idx);
         kpair->giFirst  = kernIndices[idx];
         idx = kerntab.pairs[i].right;
         if (kernIndices[idx] == (USHORT)-1)
            kernIndices[idx] = ReverseTranslate(face, idx);
         kpair->giSecond = kernIndices[idx];
         kpair->eKerningAmount = kerntab.pairs[i].value;
         kpair++;
         i++;
      }

      COPY("Returned kerning pairs: "); CATI(i); CAT("\r\n"); WRITE;
      return i; /* # items filled */
#else
      return 0;  /* no kerning support */

#endif
   }

   if (iQuery == FD_QUERY_ABC_WIDTHS)
   {
      count = cb / sizeof(ABC_TRIPLETS);

      COPY("QUERY_ABC_WIDTHS, "); CATI((int) count);
      CAT(" items, giStart = ");  CATI((int) giStart);
      if (pBuffer == NULL)
         CAT(" NULL buffer");
      CAT("\r\n"); WRITE;

      /* This call never fails - no error check needed */
      TT_Get_Face_Properties( face->face, &properties );

      pt = (ABC_TRIPLETS*)pBuffer;
      for (i = giStart; i < giStart + count; i++, pt++)
      {
         int                    index;
         unsigned short         wid;
         static unsigned short  adv_widths [2];
         static unsigned short  adv_heights[2];

         static unsigned short  widths[2], heights[2];
         static short           lefts [2], tops   [2];

         index = PM2TT( face->charMap,
                        face->charMode,
                        i );

         /* get advances and bearings */
         if (size->vertical && properties.vertical && 0) /* TODO: enable */
           error = TT_Get_Face_Metrics( face->face, index, index,
                                        lefts, adv_widths, tops, adv_heights );
         else
           error = TT_Get_Face_Metrics( face->face, index, index,
                                        lefts, adv_widths, NULL, NULL );

         if (error)
           goto Broken_Glyph;

         /* skip complicated calculations for fixed fonts */
         if (face->flags & FC_FLAG_FIXED_WIDTH) {
            wid = adv_widths[0] - lefts[0];
         }
         else {   /* proportianal font, it gets trickier */
            /* store glyph widths for DBCS fonts
               - needed for reasonable performance */
            if (face->flags & FC_FLAG_DBCS_FACE) {
               if (face->widths == NULL) {
                  error = ALLOC(face->widths,
                                properties.num_Glyphs * sizeof (USHORT));
                  if (error)
                     goto Broken_Glyph;   /* this error really shouldn't happen */

                  /* tag all entries as unused */
                  memset(face->widths, 0xFF,
                         properties.num_Glyphs * sizeof (USHORT));
               }
               if (face->widths[index] == 0xFFFF) { /* get from file if needed */
                  error = TT_Get_Face_Widths( face->face, index, index,
                                              widths, heights );
                  if (error)
                     goto Broken_Glyph;

                  /* save for later */
                  wid = face->widths[index] = widths[0];
               }
               else
                  wid = face->widths[index];
            }
            /* 'small' font, no need to remember widths, OS/2 takes care of it */
            else {
               /* get width or height - use ftxwidth.c */
               error = TT_Get_Face_Widths( face->face, index, index,
                                           widths, heights );
               if (error)
                 goto Broken_Glyph;

               wid = widths[0];
            }
         }

         if (size->vertical && !is_HALFCHAR(i))
         {
            if (properties.vertical && 0) /* TODO: enable */
            {
              pt->lA = tops[0];
              pt->ulB = heights[0];
              pt->lC = adv_heights[0] - pt->lA - pt->ulB;
            }
            else
            {
              pt->lA  = pt->lC = 0;
              pt->ulB = properties.os2->usWinAscent +
                        properties.os2->usWinDescent;
            }

         }
         else
         {
           pt->lA  = lefts[0];
           pt->ulB = wid;
           pt->lC  = adv_widths[0] - pt->lA - pt->ulB;
         }

#ifdef NETSCAPE_FIX
         if (face->charMode != TRANSLATE_SYMBOL &&
             !size->vertical) {
            if (face->flags & FC_FLAG_FIXED_WIDTH) {
               pt->ulB = pt->ulB + pt->lA + pt->lC;
               pt->lA  = 0;
               pt->lC  = 0;
            } else if (i == 32) {
               /* return nonzero B width for 'space' */
               pt->ulB = adv_widths[0] - 2 * lefts[0];
               pt->lC  = lefts[0];
            }
         }
#endif
         continue;

     Broken_Glyph:  /* handle broken glyphs gracefully */
           pt->lA = pt->lC = 0;

           if (size->vertical && !is_HALFCHAR(i))
             pt->ulB = properties.os2->usWinAscent +
                      properties.os2->usWinDescent;
           else
             pt->ulB = properties.horizontal->xMax_Extent;

      }
   }

   TT_Flush_Face(face->face);
   return count; /* number of entries filled in */

Fail:
   TT_Flush_Face(face->face);
   return -1;
}

/****************************************************************************/
/*                                                                          */
/* QueryCharAttr :                                                          */
/*                                                                          */
/*  Return glyph attributes, basically glyph's bit-map or outline           */
/*  some variables are declared static to conserve stack space.             */
/*                                                                          */
LONG _System QueryCharAttr( HFC             hfc,
                            PCHARATTR       pCharAttr,
                            PBITMAPMETRICS  pbmm )
{
   static   TT_Raster_Map  bitmap;
   static   TT_Outline     outline;
   static   TT_BBox        bbox;

   PFontSize  size;
   PFontFace  face;
   LONG       temp;
   PBYTE      pb;
   int        i, j;
   ULONG      cb;

   size = getFontSize(hfc);
   if (!size)
      ERRRET(-1) /* error, invalid context handle */

   face = &(size->file->faces[size->faceIndex]);

   error = TT_Load_Glyph( size->instance,
                          face->glyph,
                          PM2TT( face->charMap,
                                 face->charMode,
                                 pCharAttr->gi),
                          TTLOAD_DEFAULT);

   if (error)
   {
      if (i == 0)
         ERET1( Fail )  /* this font's no good, return error */
      else
      { /* try to recover quietly */
         error = TT_Load_Glyph( size->instance,
                                face->glyph,
                                0,
                                TTLOAD_DEFAULT);
         if (error) {
            COPY("Error code is "); CATI(error); CAT("\r\n"); WRITE;
            ERET1( Fail );
         }
      }
   }

   TT_Flush_Face( face->face );

   error = TT_Get_Glyph_Outline( face->glyph, &outline );
   if (error)
      ERRRET(-1);

   /* --- Vertical fonts handling----------------------------------- */

   if (size->vertical && !is_HALFCHAR(pCharAttr->gi)) {
      TT_Matrix           vertMatrix;

      vertMatrix.xx =  0x00000;
      vertMatrix.xy = -0x10000;
      vertMatrix.yx =  0x10000;
      vertMatrix.yy =  0x00000;
      TT_Get_Outline_BBox( &outline, &bbox );

      /* rotate outline 90 degrees counterclockwise */
      TT_Transform_Outline(&outline, &vertMatrix);

      /* move outline to the right to adjust for rotation */
      TT_Translate_Outline(&outline, bbox.yMax, 0);
      /* move outline down a bit */
      TT_Translate_Outline(&outline, 0, bbox.yMin);
   }

   if (size->transformed)
     TT_Transform_Outline( &outline, &size->matrix );

   /* --- Outline processing --------------------------------------- */

   if ( pCharAttr->iQuery & FD_QUERY_OUTLINE )
   {
     if (pCharAttr->cbLen == 0)      /* send required outline size in bytes */
       return GetOutlineLen( &outline );

     return GetOutline( &outline, pCharAttr->pBuffer );
   }

   /* --- Bitmap processing ---------------------------------------- */

   TT_Get_Outline_BBox( &outline, &bbox );

   /* the following seems to be necessary for rotated glyphs */
   if (size->transformed) {
      bbox.xMax = bbox.xMin = 0;
      for (i = 0; i < outline.n_points; i++) {
         if (bbox.xMin  > outline.points[i].x)
            bbox.xMin = outline.points[i].x;
         if (bbox.xMax  < outline.points[i].x)
            bbox.xMax = outline.points[i].x;
      }
   }
   /* grid-fit the bbox */
   bbox.xMin &= -64;
   bbox.yMin &= -64;

   bbox.xMax = (bbox.xMax+63) & -64;
   bbox.yMax = (bbox.yMax+63) & -64;

   if (pCharAttr->iQuery & FD_QUERY_BITMAPMETRICS)
   {
      /* fill in bitmap metrics */
      /* metrics values are in 26.6 format ! */
      pbmm->sizlExtent.cx = (bbox.xMax - bbox.xMin) >> 6;
      pbmm->sizlExtent.cy = (bbox.yMax - bbox.yMin) >> 6;
      pbmm->cyAscent      = 0;
      pbmm->pfxOrigin.x   = bbox.xMin << 10;
      pbmm->pfxOrigin.y   = bbox.yMax << 10;

      if (!(pCharAttr->iQuery & FD_QUERY_CHARIMAGE))
         return sizeof(*pbmm);
   }

   /* --- actual bitmap processing here --- */
   if (pCharAttr->iQuery & FD_QUERY_CHARIMAGE)
   {
      /* values in 26.6 format ?!? */
      bitmap.width  = (bbox.xMax - bbox.xMin) >> 6;
      bitmap.rows   = (bbox.yMax - bbox.yMin) >> 6;
      /* width rounded up to nearest multiple of 4 */
      bitmap.cols   = ((bitmap.width + 31) / 8) & -4;
      bitmap.flow   = TT_Flow_Down;
      bitmap.bitmap = pCharAttr->pBuffer;
      bitmap.size   = bitmap.rows * bitmap.cols;

      if (pCharAttr->cbLen == 0)
         return bitmap.size;

      if (bitmap.size > pCharAttr->cbLen)
         ERRRET(-1)     /* otherwise we might overwrite something */

      /* clean provided buffer (unfortunately necessary) */
      memset(bitmap.bitmap, 0, pCharAttr->cbLen);

      error = TT_Get_Glyph_Bitmap( face->glyph,
                                   &bitmap,
                                   -bbox.xMin,
                                   -bbox.yMin );
      if (error)
         ERRRET(-1); /* engine error */

      return bitmap.size; /* return # of bytes */
   }
   ERRRET(-1) /* error */

Fail:
   TT_Flush_Face(face->face);
   return -1;
}

/****************************************************************************/
/*                                                                          */
/* QueryFullFaces :                                                         */
/*                                                                          */
/*  Query names of all faces in this file                                   */
/*                                                                          */
LONG _System QueryFullFaces( HFF     hff,
                             PVOID   pBuff,
                             PULONG  buflen,
                             PULONG  cFontCount,
                             ULONG   cStart )
{
   COPY("!QueryFullFaces: hff = "); CATI((int) hff); CAT("\r\n"); WRITE;
   ERRRET(-1) /* error ? */
}

/*---------------------------------------------------------------------------*/
/* end of exported functions */
/*---------------------------------------------------------------------------*/


/****************************************************************************/
/* LimitsInit reads OS2.INI and sets up max_open_files limit, possibly      */
/* other variables as well.                                                 */
/*                                                                          */
static  void LimitsInit(void) {
   char  cBuffer[25];  /* ought to be enough */

   if (PrfQueryProfileString(HINI_USERPROFILE, "FreeType/2", "OPENFACES",
                             NULL, cBuffer, sizeof(cBuffer)) > 0) {
      max_open_files = atoi(cBuffer);

      if (max_open_files < 8)  /* ensure limit isn't too low */
         max_open_files = 8;
   }
   else
      max_open_files = 12;   /* reasonable default */
}


/****************************************************************************/
/* my_itoa is used only in the following function GetUdcInfo.               */
/* Works pretty much like expected.                                         */
/*                                                                          */
void    my_itoa(int num, char *cp) {
    char    temp[10];
    int     i = 0;

    do {
        temp[i++] = (num % 10) + '0';
        num /= 10;
    } while (num);                  /* enddo */

    while (i--) {
        *cp++ = temp[i];
    }                               /* endwhile */
    *cp = '\0';
}

/****************************************************************************/
/* GetUdcInfo determines the UDC ranges used                                */
/*                                                                          */
VOID    GetUdcInfo(VOID) {
    ULONG   ulUdc, ulUdcInfo, i;
    PVOID   gPtr;
    HINI    hini;
    CHAR    szCpStr[10] = "CP";

    DosQueryCp(sizeof(ulCp), (ULONG*)&ulCp, &i);  /* find out default codepage */
    my_itoa((INT) ulCp, szCpStr + 2);     /* convert to ASCII          */

}

/****************************************************************************/
/* LangInit determines language used at DLL startup, non-zero return value  */
/* means error.                                                             */
/* This code is crucial, because it determines behaviour of the font driver */
/* with regard to language encodings it will use.                           */
static  ULONG LangInit(void) {
   COUNTRYCODE cc = {0, 0};
   COUNTRYINFO ci;
   ULONG       cilen;

   isGBK = FALSE;

   GetUdcInfo();           /* get User Defined Character info */

   /* get country info; ci.country then contains country code */
   if (DosQueryCtryInfo(sizeof(ci), &cc, &ci, &cilen))
      return -1;
   /* get DBCS lead byte values for later use */
   DosQueryDBCSEnv(sizeof(DBCSLead), &cc, DBCSLead);

   uLastGlyph = 383;
   switch (ci.country) {
      case 81:            /* Japan */
         iLangId = TT_MS_LANGID_JAPANESE_JAPAN;
         ScriptTag = *(ULONG *) "kana";
         LangSysTag = *(ULONG *) "JAN ";
         pGlyphlistName = "PMJPN";
         uLastGlyph = 890;
         break;

      case 88:            /* Taiwan */
         iLangId = TT_MS_LANGID_CHINESE_TAIWAN;
         ScriptTag = *(ULONG *) "kana";
         LangSysTag = *(ULONG *) "CHT ";
         pGlyphlistName = "PMCHT";
         break;

      case 86:            /* People's Republic of China */
         if (ci.codepage == 1386 || ulCp[0] == 1386 || ulCp[1] == 1386) {
            isGBK = TRUE;
         }               /* endif */
         iLangId = TT_MS_LANGID_CHINESE_PRC;
         ScriptTag = *(ULONG *) "kana";
         LangSysTag = *(ULONG *) "CHS ";
         pGlyphlistName = "PMPRC";
         break;

      case 82:            /* Korea */
         iLangId = TT_MS_LANGID_KOREAN_EXTENDED_WANSUNG_KOREA;
         ScriptTag = *(ULONG *) "hang";
         LangSysTag = *(ULONG *) "KOR ";
         pGlyphlistName = "PMKOR";
         uLastGlyph = 949;
         break;

      case 30:            /* Greece  - for Alex! */
         iLangId = TT_MS_LANGID_GREEK_GREECE;

      default:            /* none of the above countries */
         ScriptTag = *(ULONG *) "";
         LangSysTag = *(ULONG *) "";
         break;
   }                      /* endswitch */

   return 0;
}

/****************************************************************************/
/*                                                                          */
/* FirstInit :                                                              */
/*                                                                          */
/*  Called when font driver is loaded for the first time. Performs the      */
/* necessary one-time initialization.                                       */
ULONG  FirstInit(void) {
   LONG   lReqCount;
   ULONG  ulCurMaxFH;

   #ifdef DEBUG
      ULONG Action;
   #endif /* DEBUG */
   #ifdef DEBUG
      DosOpen("C:\\FTIFI.LOG", &LogHandle, &Action, 0, FILE_NORMAL,
              OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_REPLACE_IF_EXISTS,
              OPEN_FLAGS_NO_CACHE | OPEN_FLAGS_WRITE_THROUGH |
              OPEN_FLAGS_SEQUENTIAL | OPEN_SHARE_DENYWRITE | OPEN_ACCESS_WRITEONLY,
              NULL);
      COPY("FreeType/2 loaded.\r\n");
      WRITE;
   #endif /* DEBUG */

   /* increase # of file handles by five to be on the safe side */
   lReqCount = 5;
   DosSetRelMaxFH(&lReqCount, &ulCurMaxFH);
   error = TT_Init_FreeType(&engine);   /* turn on the FT engine */
   if (error)
      return 0;     /* exit immediately */
   error = TT_Init_Kerning_Extension(engine); /* load kerning support */
   COPY("FreeType Init called\r\n");
   WRITE;

   if (LangInit())      /* initialize NLS */
      return 0;         /* exit on error  */
   COPY("NLS initialized.\r\n");
   WRITE;

   LimitsInit();  /* initialize max_open_files */
   COPY("Open faces limit set to "); CATI(max_open_files); CAT("\r\n");
   WRITE;

   if (error)
      return 0;     /* exit immediately */
   COPY("Initialization successful.\r\n");
   WRITE;
   return 1;
}


/****************************************************************************/
/*                                                                          */
/* FinalTerm :                                                              */
/*                                                                          */
/*  Called when font driver is unloaded for the last time time. Performs    */
/* final clean-up, shuts down engine etc.                                   */
ULONG  FinalTerm(void) {
   PListElement  cur;
   PListElement  tmp;

   /* throw away elements from 'free elements' list */
   cur = free_elements;
   while (cur != NULL) {
      tmp = cur;
      cur = cur->next;
      FREE(tmp);
   }

   /* turn off engine */
   TT_Done_FreeType(engine);

   #ifdef DEBUG
      COPY("FreeType/2 terminated.\r\n");
      WRITE;
      DosClose(LogHandle);
   #endif
   return 1;
}
/****************************************************************************/
/*                                                                          */
/* _DLL_InitTerm :                                                          */
/*                                                                          */
/*  This is the DLL Initialization/termination function. It initializes     */
/*  the FreeType engine and some internal structures at startup. It cleans  */
/*  up the UCONV cache at process termination.                              */
ULONG _System _DLL_InitTerm(ULONG hModule, ULONG ulFlag) {
   switch (ulFlag) {
      case 0:             /* initializing */
         if (++ulProcessCount == 1)
            return FirstInit();  /* loaded for the first time */
         else
            return 1;

      case 1:  {          /* terminating */
         int   i;
         /* clean UCONV cache */
         #ifdef USE_UCONV
            CleanUCONVCache();
         #endif
         if(--ulProcessCount == 0)
            return FinalTerm();
         else
            return 1;
      }
   }
   return 0;
}

/****************************************************************************/
/*                                                                          */
/* interfaceSEId (Interface-specific Encoding Id) determines what encoding  */
/* the font driver should use if a font includes a Unicode encoding.        */
/*                                                                          */
LONG    interfaceSEId(TT_Face face, BOOL UDCflag, LONG encoding) {
    ULONG   range1 = 0;
    ULONG   bits, mask;
    TT_OS2  *pOS2;
    static  TT_Face_Properties  props;

    TT_Get_Face_Properties(face, &props);
    pOS2 = props.os2;

    if (encoding == PSEID_UNICODE) {

       /* if font is 'small', use PM383; this is done because of DBCS
          systems */
       if (!UDCflag && props.num_Glyphs < 1024) {
          encoding = PSEID_PM383;
       } else if (pOS2->version >= 1) {
          /*
           * *  OS/2 table version 1 and later contains codepage *
           * bitfield to support multiple codepages.
           */
          range1 = pOS2->ulCodePageRange1;
          bits = 0;

          if (range1 & OS2_CP1_ANSI_OEM_JAPANESE_JIS)
             bits++;
          if (range1 & OS2_CP1_ANSI_OEM_CHINESE_SIMPLIFIED)
             bits++;
          if (range1 & OS2_CP1_ANSI_OEM_CHINESE_TRADITIONAL)
             bits++;
          if (range1 & OS2_CP1_ANSI_OEM_KOREAN_WANSUNG)
             bits++;
          if (range1 & OS2_CP1_ANSI_OEM_KOREAN_JOHAB)
             bits++;

          /* Note: if font supports more than one of the following codepages,
           * encoding is left at PSEID_UNICODE!
           */
          if (bits == 1) {
             switch (range1) {
                case OS2_CP1_ANSI_OEM_JAPANESE_JIS:
                   encoding = PSEID_SHIFTJIS;
                   break;
                case OS2_CP1_ANSI_OEM_CHINESE_SIMPLIFIED:
                   encoding = PSEID_PRC;
                   break;
                case OS2_CP1_ANSI_OEM_CHINESE_TRADITIONAL:
                   encoding = PSEID_BIG5;
                   break;
                case OS2_CP1_ANSI_OEM_KOREAN_WANSUNG:
                   encoding = PSEID_WANSUNG;
                   break;
                case OS2_CP1_ANSI_OEM_KOREAN_JOHAB:
                   encoding = PSEID_JOHAB;
                   break;
                default:
                   break;
             }                   /* endswitch */
          }                      /* endif */
       } else {
          /*
           * The codepage range bitfield is not available.
           * Codepage must be assumed from the COUNTRY setting.
           * This means the user is on his own.
           */

          switch (iLangId) {
             case TT_MS_LANGID_JAPANESE_JAPAN:
                encoding = PSEID_SHIFTJIS;
                break;
             case TT_MS_LANGID_CHINESE_PRC:
             case TT_MS_LANGID_CHINESE_SINGAPORE:
                encoding = PSEID_PRC;
                break;
             case TT_MS_LANGID_CHINESE_TAIWAN:
             case TT_MS_LANGID_CHINESE_HONG_KONG:
                encoding = PSEID_BIG5;
                break;
             case TT_MS_LANGID_KOREAN_EXTENDED_WANSUNG_KOREA:
                encoding = PSEID_WANSUNG;
                break;
             case TT_MS_LANGID_KOREAN_JOHAB_KOREA:
                encoding = PSEID_JOHAB;
                break;
          }

       }
    }
    return encoding;
}

/****************************************************************************/
/*                                                                          */
/* LookupName :                                                             */
/*                                                                          */
/*   Look for a TrueType name by index, prefer current language             */
/*                                                                          */
static  char*  LookupName(TT_Face face,  int index )
{
   static char name_buffer[FACESIZE + 2];
   int    name_len = 0;
   int i, j, n;

   USHORT platform, encoding, language, id;
   char*  string;
   USHORT string_len;

   int    found;

   n = TT_Get_Name_Count( face );
   if ( n < 0 )
      return NULL;

   for ( i = 0; i < n; i++ )
   {
      TT_Get_Name_ID( face, i, &platform, &encoding, &language, &id );
      TT_Get_Name_String( face, i, &string, &string_len );

      if ( id == index )
      {
        found = 0;

        /* Try to find an appropriate name */
        if ( platform == TT_PLATFORM_MICROSOFT )
          for ( j = 5; j >= 0; j-- )
            if ( encoding == j )  /* Microsoft ? */
              switch (language)
              {
                case TT_MS_LANGID_CHINESE_TAIWAN:
                   if (encoding == PSEID_PRC)
                      found = 1;
                   break;

                case TT_MS_LANGID_JAPANESE_JAPAN:
                   if (encoding == PSEID_SHIFTJIS)
                      found = 1;
                   break;

                /* these aren't all possibilities; just the most likely ones */
                case TT_MS_LANGID_ENGLISH_UNITED_STATES  :
                case TT_MS_LANGID_ENGLISH_UNITED_KINGDOM :
                case TT_MS_LANGID_ENGLISH_AUSTRALIA      :
                case TT_MS_LANGID_ENGLISH_CANADA         :
                case TT_MS_LANGID_ENGLISH_NEW_ZEALAND    :
                case TT_MS_LANGID_ENGLISH_IRELAND        :
                case TT_MS_LANGID_ENGLISH_SOUTH_AFRICA   :
                             found = 1;
                             break;
              }

        if ( !found && platform == 0 && language == 0 )
          found = 1;

        if (found)
        {
          if (language == TT_MS_LANGID_CHINESE_TAIWAN ||
              language == TT_MS_LANGID_JAPANESE_JAPAN) {
             /* it's a DBCS string, copy everything except NULLs */
             int i,j;
             if (string_len > FACESIZE - 1)
                string_len = FACESIZE - 1;

             for (i=0, j=0; i<string_len; i++)
               if (string[i] != '\0')
                  name_buffer[j++] = string[i];
             name_buffer[j] = '\0';

             return name_buffer;
          }
          else {
             /* assume it's an ASCII string in Unicode, just skip the
                zeros  */
             if ( string_len > FACESIZE * 2)
               string_len = FACESIZE * 2;

             name_len = 0;

             for ( i = 1; i < string_len; i += 2 )
               name_buffer[name_len++] = string[i];

             name_buffer[name_len] = '\0';

             return name_buffer;
           }
        }
      }
   }

   /* Not found */
   return NULL;
}

/****************************************************************************/
/*                                                                          */
/* GetCharMap :                                                             */
/*                                                                          */
/*  A function to find a suitable charmap, searching in the following       */
/*  order of importance :                                                   */
/*                                                                          */
/*   1) Windows Unicode                                                     */
/*   2) Apple Unicode                                                       */
/*   3) ROC (Taiwan)                                                        */
/*   4) ShiftJIS (Japan)                                                    */
/*   5) Apple Roman                                                         */
/*   6) Windows Symbol - not really supported                               */
/*                                                                          */
/* High word of returned ULONG contains type of encoding                    */
/*                                                                          */
static  ULONG GetCharmap(TT_Face face)
{
   int    n;      /* # of encodings (charmaps) available */
   USHORT platform, encoding;
   int    i, best, bestVal, val;

   n = TT_Get_CharMap_Count(face);

   if (n < 0)      /* no encodings at all; don't yet know what the best course of action would be */
      ERRRET(-1)   /* such font should probably be rejected */

   bestVal = 16;
   best    = -1;

   for (i = 0; i < n; i++)
   {
     TT_Get_CharMap_ID( face, i, &platform, &encoding );

     /* Windows Unicode is the highest encoding, return immediately */
     /* if we find it..                                             */
     if ( platform == TT_PLATFORM_MICROSOFT && encoding == TT_MS_ID_UNICODE_CS)
       return i;

     /* otherwise, compare it to the best encoding found */
     val = -1;
     if (platform == TT_PLATFORM_APPLE_UNICODE)
        val = 2;
     else if (platform == TT_PLATFORM_MICROSOFT
           && encoding == TT_MS_ID_BIG_5)
        val = 3;
     else if (platform == TT_PLATFORM_MICROSOFT
           && encoding == TT_MS_ID_SJIS)
        val = 4;
     else if (platform == TT_PLATFORM_MACINTOSH
           && encoding == TT_MAC_ID_ROMAN)
        val = 5;
     else if (platform == TT_PLATFORM_MICROSOFT
           && encoding == TT_MS_ID_SYMBOL_CS)
        val = 6;

     if (val > 0 && val <= bestVal)
     {
       bestVal = val;
       best    = i;
     }
   }

   if (i < 0)
     return 0;           /* we didn't find any suitable encoding !! */

   if (bestVal == 3)        /* Taiwanese font */
     best |= ( TRANSLATE_BIG5 << 16 );

   if (bestVal == 4)        /* Japanese font */
     best |= ( TRANSLATE_SJIS << 16 );

   if (bestVal == 5)        /* for Apple Roman encoding only, this      */
     best |= ( TRANSLATE_SYMBOL << 16 );   /* means no translation should be performed */

   return best;
}

/****************************************************************************/
/*                                                                          */
/* GetOutlineLen :                                                          */
/*                                                                          */
/*   Used to compute the size of an outline once it is converted to         */
/*   OS/2's specific format. The translation is performed by the later      */
/*   function called simply "GetOultine".                                   */
/*                                                                          */
static  int GetOutlineLen(TT_Outline *ol)
{
   int    index;     /* current point's index */
   BOOL   on_curve;  /* current point's state */
   int    i, start = 0;
   int    first, last;
   ULONG  cb = 0;

   /* loop thru all contours in a glyph */
   for ( i = 0; i < ol->n_contours; i++ ) {

      cb += sizeof(POLYGONHEADER);

      first = start;
      last  = ol->contours[i];

      on_curve = (ol->flags[first] & 1);
      index    = first;

      /* process each contour point individually */
      while ( index < last ) {
         index++;

         if ( on_curve ) {
            /* the previous point was on the curve */
            on_curve = ( ol->flags[index] & 1 );
            if ( on_curve ) {
               /* two successive on points => emit segment */
               cb += sizeof(PRIMLINE);
            }
         }
         else {
            /* the previous point was off the curve */
            on_curve = ( ol->flags[index] & 1 );
            if ( on_curve ) {
               /* reaching an `on' point */
               cb += sizeof(PRIMSPLINE);
            }
            else {
               /* two successive `off' points => create middle point */
               cb += sizeof(PRIMSPLINE);
            }
         }
      }

      /* end of contour, close curve cleanly */
      if ( ol->flags[first] & 1 )
      {
        if ( on_curve )
           cb += sizeof(PRIMLINE);
        else
           cb += sizeof(PRIMSPLINE);
      }
      else
        if (!on_curve)
           cb += sizeof(PRIMSPLINE);

      start = ol->contours[i] + 1;

   }
   return cb; /* return # bytes used */
}

/****************************************************************************/
/*                                                                          */
/*  a few global variables used in the following functions                  */
/*                                                                          */
static ULONG          cb = 0, polycb;
static LONG           lastX, lastY;
static PBYTE          pb;
static POINTFX        Q, R;
static POLYGONHEADER  hdr = {0, FD_POLYGON_TYPE};
static PRIMLINE       line = {FD_PRIM_LINE};
static PRIMSPLINE     spline = {FD_PRIM_SPLINE};

/****************************************************************************/
/*                                                                          */
/* LineFrom :                                                               */
/*                                                                          */
/*   add a line segment to the PM outline that GetOultine is currently      */
/*   building.                                                              */
/*                                                                          */
static  void Line_From(LONG x, LONG y) {
   line.pte.x = x << 10;
   line.pte.y = y << 10;
   /* store to output buffer */
   memcpy(&(pb[cb]), &line, sizeof(line));
   cb     += sizeof(PRIMLINE);
   polycb += sizeof(PRIMLINE);
}


/****************************************************************************/
/*                                                                          */
/* BezierFrom :                                                             */
/*                                                                          */
/*   add a bezier arc to the PM outline that GetOutline is currently        */
/*   buidling. The second-order Bezier is trivially converted to its        */
/*   equivalent third-order form.                                           */
/*                                                                          */
static  void Bezier_From( LONG x0, LONG y0, LONG x2, LONG y2, LONG x1, LONG y1 ) {
   spline.pte[0].x = x0 << 10;
   spline.pte[0].y = y0 << 10;
   /* convert from second-order to cubic Bezier spline */
   Q.x = (x0 + 2 * x1) / 3;
   Q.y = (y0 + 2 * y1) / 3;
   R.x = (x2 + 2 * x1) / 3;
   R.y = (y2 + 2 * y1) / 3;
   spline.pte[1].x = Q.x << 10;
   spline.pte[1].y = Q.y << 10;
   spline.pte[2].x = R.x << 10;
   spline.pte[2].y = R.y << 10;
   /* store to output buffer */
   memcpy(&(pb[cb]), &spline, sizeof(spline));
   cb     += sizeof(PRIMSPLINE);
   polycb += sizeof(PRIMSPLINE);
}


/****************************************************************************/
/*                                                                          */
/* GetOutline :                                                             */
/*                                                                          */
/*   Translate a FreeType glyph outline into PM format. The buffer is       */
/*   expected to be of the size returned by a previous call to the          */
/*   function GetOutlineLen().                                              */
/*                                                                          */
/*   This code is taken right from the FreeType ttraster.c source, and      */
/*   subsequently modified to emit PM segments and arcs.                    */
/*                                                                          */
static  int GetOutline(TT_Outline *ol, PBYTE pbuf) {
   LONG   x,  y;   /* current point                */
   LONG   cx, cy;  /* current Bezier control point */
   LONG   mx, my;  /* current middle point         */
   LONG   x_first, y_first;  /* first point's coordinates */
   LONG   x_last,  y_last;   /* last point's coordinates  */

   int    index;     /* current point's index */
   BOOL   on_curve;  /* current point's state */
   int    i, start = 0;
   int    first, last;
   ULONG  polystart;

   pb = pbuf;
   cb = 0;

   /* loop thru all contours in a glyph */
   for ( i = 0; i < ol->n_contours; i++ ) {

      polystart = cb;  /* save this polygon's start offset */
      polycb = sizeof(POLYGONHEADER); /* size of this polygon */
      cb += sizeof(POLYGONHEADER);

      first = start;
      last = ol->contours[i];

      x_first = ol->points[first].x;
      y_first = ol->points[first].y;

      x_last  = ol->points[last].x;
      y_last  = ol->points[last].y;

      lastX = cx = x_first;
      lastY = cy = y_first;

      on_curve = (ol->flags[first] & 1);
      index    = first;

      /* check first point to determine origin */
      if ( !on_curve ) {
         /* first point is off the curve.  Yes, this happens... */
         if ( ol->flags[last] & 1 ) {
            lastX = x_last;  /* start at last point if it */
            lastY = y_last;  /* is on the curve           */
         }
         else {
            /* if both first and last points are off the curve, */
            /* start at their middle and record its position    */
            /* for closure                                      */
            lastX = (lastX + x_last)/2;
            lastY = (lastY + y_last)/2;

            x_last = lastX;
            y_last = lastY;
         }
      }

      /* now process each contour point individually */
      while ( index < last ) {
         index++;
         x = ( ol->points[index].x );
         y = ( ol->points[index].y );

         if ( on_curve ) {
            /* the previous point was on the curve */
            on_curve = ( ol->flags[index] & 1 );
            if ( on_curve ) {
               /* two successive on points => emit segment */
               Line_From( lastX, lastY ); /*x, y*/
               lastX = x;
               lastY = y;
            }
            else {
               /* else, keep current control point for next bezier */
               cx = x;
               cy = y;
            }
         }
         else {
            /* the previous point was off the curve */
            on_curve = ( ol->flags[index] & 1 );
            if ( on_curve ) {
               /* reaching an `on' point */
               Bezier_From(lastX, lastY, x, y, cx, cy );
               lastX = x;
               lastY = y;
            }
            else {
               /* two successive `off' points => create middle point */
               mx = (cx + x) / 2;
               my = (cy + y)/2;

               Bezier_From( lastX, lastY, mx, my, cx, cy );
               lastX = mx;
               lastY = my;

               cx = x;
               cy = y;
            }
         }
      }

      /* end of contour, close curve cleanly */
      if ( ol->flags[first] & 1 ) {
         if ( on_curve )
            Line_From( lastX, lastY); /* x_first, y_first );*/
         else
            Bezier_From( lastX, lastY, x_first, y_first, cx, cy );
      }
      else
        if (!on_curve)
          Bezier_From( lastX, lastY, x_last, y_last, cx, cy );

      start = ol->contours[i] + 1;

      hdr.cb = polycb;
      memcpy(&(pb[polystart]), &hdr, sizeof(hdr));

   }
   return cb; /* return # bytes used */
}