File: plcore.c

package info (click to toggle)
emboss 6.6.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 571,248 kB
  • ctags: 39,971
  • sloc: ansic: 460,578; java: 29,439; perl: 13,573; sh: 12,740; makefile: 3,275; csh: 706; asm: 351; xml: 239; pascal: 237; modula3: 8
file content (3458 lines) | stat: -rw-r--r-- 93,528 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
/* $Id: plcore.c,v 1.14 2007/10/24 13:14:43 ajb Exp $

	Central dispatch facility for PLplot.
	Also contains the PLplot main data structures, external access
	routines, and initialization calls.

	This stuff used to be in "dispatch.h", "dispatch.c", and "base.c".


  Copyright (C) 2004  Joao Cardoso
  Copyright (C) 2004, 2005  Rafael Laboissiere
  Copyright (C) 2004, 2006  Andrew Ross
  Copyright (C) 2004  Andrew Roach
  Copyright (C) 2005  Alan W. Irwin
  Copyright (C) 2005  Thomas J. Duck

  This file is part of PLplot.

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

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

  You should have received a copy of the GNU Library General Public License
  along with PLplot; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

*/

#define DEBUG

#define NEED_PLDEBUG
#include "plcore.h"

#ifdef ENABLE_DYNDRIVERS
#include <ltdl.h>
#endif

/*--------------------------------------------------------------------------*\
 * Driver Interface
 *
 * These routines are the low-level interface to the driver -- all calls to
 * driver functions must pass through here.  For implementing driver-
 * specific functions, the escape function is provided.  The command stream
 * gets duplicated to the plot buffer here.
 *
 * All functions that result in graphics actually being plotted (rather than
 * just a change of state) are filtered as necessary before being passed on.
 * The default settings do not require any filtering, i.e.  PLplot physical
 * coordinates are the same as the device physical coordinates (currently
 * this can't be changed anyway), and a global view equal to the entire page
 * is used.
 *
 * The reason one wants to put view-specific filtering here is that if
 * enabled, the plot buffer should receive the unfiltered data stream.  This
 * allows a specific view to be used from an interactive device (e.g. TCL/TK
 * driver) but be restored to the full view at any time merely by
 * reprocessing the contents of the plot buffer.
 *
 * The metafile, on the other hand, *should* be affected by changes in the
 * view, since this is a crucial editing capability.  It is recommended that
 * the initial metafile be created without a restricted global view, and
 * modification of the view done on a per-plot basis as desired during
 * subsequent processing.
 *
\*--------------------------------------------------------------------------*/

enum {AT_BOP, DRAWING, AT_EOP};

/* Initialize device. */
/* The plot buffer must be called last. */

/* The following array of chars is used both here and in plsym.c for
 * translating the Greek characters from the #g escape sequences into
 * the Hershey and Unicode codings
 */
const char plP_greek_mnemonic[] = "ABGDEZYHIKLMNCOPRSTUFXQWabgdezyhiklmncoprstufxqw";

void
plP_init(void)
{
    plsc->page_status = AT_EOP;

    (*plsc->dispatch_table->pl_init) ((struct PLStream_struct *) plsc);

    if (plsc->plbuf_write)
	plbuf_init(plsc);
}

/* End of page */
/* The plot buffer must be called first. */
/* Ignore instruction if already at eop. */

void
plP_eop(void)
{
    int skip_driver_eop = 0;

    if (plsc->page_status == AT_EOP)
	return;

    plsc->page_status = AT_EOP;

    if (plsc->plbuf_write)
	plbuf_eop(plsc);

/* Call user eop handler if present. */

    if (plsc->eop_handler != NULL)
	(*plsc->eop_handler) (plsc->eop_data, &skip_driver_eop);

    if (!skip_driver_eop)
	(*plsc->dispatch_table->pl_eop) ((struct PLStream_struct *) plsc);
}

/* Set up new page. */
/* The plot buffer must be called last. */
/* Ignore if already at bop. */
/* It's not actually necessary to be AT_EOP here, so don't check for it. */

void
plP_bop(void)
{
    int skip_driver_bop = 0;

    plP_subpInit();
    if (plsc->page_status == AT_BOP)
	return;

    plsc->page_status = AT_BOP;
    plsc->nplwin = 0;

/* Call user bop handler if present. */

    if (plsc->bop_handler != NULL)
	(*plsc->bop_handler) (plsc->bop_data, &skip_driver_bop);

    if (!skip_driver_bop)
	(*plsc->dispatch_table->pl_bop) ((struct PLStream_struct *) plsc);

    if (plsc->plbuf_write)
	plbuf_bop(plsc);
}

/* Tidy up device (flush buffers, close file, etc). */

void
plP_tidy(void)
{
    if (plsc->tidy) {
	(*plsc->tidy) (plsc->tidy_data);
	plsc->tidy = NULL;
	plsc->tidy_data = NULL;
    }

    (*plsc->dispatch_table->pl_tidy) ((struct PLStream_struct *) plsc);

    if (plsc->plbuf_write) {
	plbuf_tidy(plsc);
    }

    plsc->OutFile = NULL;

}

/* Change state. */

void
plP_state(PLINT op)
{
    if (plsc->plbuf_write) plbuf_state(plsc, op);

    (*plsc->dispatch_table->pl_state) ((struct PLStream_struct *) plsc, op);
}

/* Escape function, for driver-specific commands. */

void
plP_esc(PLINT op, void *ptr)
{
  PLINT clpxmi, clpxma, clpymi, clpyma;
  EscText* args;

  /* The plot buffer must be called first */
  if(plsc->plbuf_write) plbuf_esc(plsc, op, ptr);

  /* Text coordinates must pass through the driver interface filter */
  if(op==PLESC_HAS_TEXT && plsc->dev_unicode) {

    /* Apply the driver interface filter */
    if (plsc->difilt) {
      args = (EscText*)ptr;
      difilt(&(args->x),&(args->y),1,&clpxmi,&clpxma,&clpymi,&clpyma);
    }
  }

  (*plsc->dispatch_table->pl_esc) ((struct PLStream_struct *) plsc, op, ptr);
}

/* Set up plot window parameters. */
/* The plot buffer must be called first */
/* Some drivers (metafile, Tk) need access to this data */

void
plP_swin(PLWindow *plwin)
{
    PLWindow *w;
    PLINT clpxmi, clpxma, clpymi, clpyma;

/* Provide plot buffer with unfiltered window data */

    if (plsc->plbuf_write)
	plbuf_esc(plsc, PLESC_SWIN, (void *) plwin);

    w = &plsc->plwin[plsc->nplwin++ % PL_MAXWINDOWS];

    w->dxmi = plwin->dxmi;
    w->dxma = plwin->dxma;
    w->dymi = plwin->dymi;
    w->dyma = plwin->dyma;

    if (plsc->difilt) {
	xscl[0] = plP_dcpcx(w->dxmi);
	xscl[1] = plP_dcpcx(w->dxma);
	yscl[0] = plP_dcpcy(w->dymi);
	yscl[1] = plP_dcpcy(w->dyma);

	difilt(xscl, yscl, 2, &clpxmi, &clpxma, &clpymi, &clpyma);

	w->dxmi = plP_pcdcx(xscl[0]);
	w->dxma = plP_pcdcx(xscl[1]);
	w->dymi = plP_pcdcy(yscl[0]);
	w->dyma = plP_pcdcy(yscl[1]);
    }

    w->wxmi = plwin->wxmi;
    w->wxma = plwin->wxma;
    w->wymi = plwin->wymi;
    w->wyma = plwin->wyma;

/* If the driver wants to process swin commands, call it now */
/* It must use the filtered data, which it can get from *plsc */

    if (plsc->dev_swin) {
	(*plsc->dispatch_table->pl_esc) ( (struct PLStream_struct *) plsc,
                                          PLESC_SWIN, NULL );
    }
}

/*--------------------------------------------------------------------------*\
 *  Drawing commands.
\*--------------------------------------------------------------------------*/

/* Draw line between two points */
/* The plot buffer must be called first so it gets the unfiltered data */

void
plP_line(short *x, short *y)
{
    PLINT i, npts = 2, clpxmi, clpxma, clpymi, clpyma;

    plsc->page_status = DRAWING;

    if (plsc->plbuf_write)
	plbuf_line(plsc, x[0], y[0], x[1], y[1]);

    if (plsc->difilt) {
	for (i = 0; i < npts; i++) {
	    xscl[i] = x[i];
	    yscl[i] = y[i];
	}
	difilt(xscl, yscl, npts, &clpxmi, &clpxma, &clpymi, &clpyma);
	plP_pllclp(xscl, yscl, npts, clpxmi, clpxma, clpymi, clpyma, grline);
    }
    else {
	grline(x, y, npts);
    }
}

/* Draw polyline */
/* The plot buffer must be called first */

void
plP_polyline(short *x, short *y, PLINT npts)
{
    PLINT i, clpxmi, clpxma, clpymi, clpyma;

    plsc->page_status = DRAWING;

    if (plsc->plbuf_write)
	plbuf_polyline(plsc, x, y, npts);

    if (plsc->difilt) {
	for (i = 0; i < npts; i++) {
	    xscl[i] = x[i];
	    yscl[i] = y[i];
	}
	difilt(xscl, yscl, npts, &clpxmi, &clpxma, &clpymi, &clpyma);
	plP_pllclp(xscl, yscl, npts, clpxmi, clpxma, clpymi, clpyma,
		   grpolyline);
    }
    else {
	grpolyline(x, y, npts);
    }
}

/* Fill polygon */
/* The plot buffer must be called first */
/* Here if the desired area fill capability isn't present, we mock up */
/* something in software */

static int foo;

void
plP_fill(short *x, short *y, PLINT npts)
{
    PLINT i, clpxmi, clpxma, clpymi, clpyma;

    plsc->page_status = DRAWING;

    if (plsc->plbuf_write) {
	plsc->dev_npts = npts;
	plsc->dev_x = x;
	plsc->dev_y = y;
	plbuf_esc(plsc, PLESC_FILL, NULL);
    }

/* Account for driver ability to do fills */

    if (plsc->patt == 0 && ! plsc->dev_fill0) {
	if ( ! foo) {
	    plwarn("Driver does not support hardware solid fills, switching to software fill.\n");
	    foo = 1;
	}
	plsc->patt = 8;
	plpsty(plsc->patt);
    }
    if (plsc->dev_fill1) {
	plsc->patt = -ABS(plsc->patt);
    }

/* Perform fill.  Here we MUST NOT allow the software fill to pass through the
   driver interface filtering twice, else we get the infamous 2*rotation for
   software fills on orientation swaps.
*/

    if (plsc->patt > 0)
	plfill_soft(x, y, npts);

    else {
	if (plsc->difilt) {
	    for (i = 0; i < npts; i++) {
		xscl[i] = x[i];
		yscl[i] = y[i];
	    }
	    difilt(xscl, yscl, npts, &clpxmi, &clpxma, &clpymi, &clpyma);
	    plP_plfclp(xscl, yscl, npts, clpxmi, clpxma, clpymi, clpyma,
		       grfill);
	}
	else {
	    grfill(x, y, npts);
	}
    }
}

/* Account for driver ability to draw text itself */
/*
#define DEBUG_TEXT
*/

#define hex2dec( a ) isdigit(a) ? a - 48 : (toupper(a) - 65) + 10

int text2num( const char *text, char end, PLUNICODE *num);
int text2fci( const char *text, unsigned char *hexdigit,
	     unsigned char *hexpower);


/*--------------------------------------------------------------------------*\
 *  int text2num( char *text, char end, PLUNICODE *num)
 *       char *text - pointer to the text to be parsed
 *       char end   - end character (i.e. ')' or ']' to stop parsing
 *       PLUNICODE *num - pointer to an PLUNICODE to store the value
 *
 *    Function takes a string, which can be either hex or decimal,
 *    and converts it into an PLUNICODE, stopping at either a null,
 *    or the character pointed to by 'end'. It is a bit brain-dead,
 *    and probably should make more checks, but it works.
\*--------------------------------------------------------------------------*/

int text2num( const char *text, char end, PLUNICODE *num)
{
  int base=10;
  unsigned short i=0;
  *num=0;

  if (text[1]=='x')
    {
      base=16;
      i=2;
    }

  while ((text[i]!=end)&&(text[i]!=0))
    {
      *num*=base;
      *num+=hex2dec(text[i]);
      i++;
    }
  return(i);
}

/*--------------------------------------------------------------------------*\
 *  int text2fci( char *text, unsigned char *hexdigit, unsigned char *hexpower)
 *       char *text - pointer to the text to be parsed
 *       unsigned char *hexdigit - pointer to hex value that is stored.
 *       unsigned char *hexpower - pointer to hex power (left shift) that is stored.
 *
 *    Function takes a pointer to a string, which is looked up in a table
 *    to determine the corresponding FCI (font characterization integer)
 *    hex digit value and hex power (left shift).  All matched strings
 *    start with "<" and end with the two characters "/>".
 *    If the lookup succeeds, hexdigit and hexpower are set to the appropriate
 *    values in the table, and the function returns the number of characters
 *    in text that are consumed by the matching string in the table lookup.
 *
 *    If the lookup fails, hexdigit is set to 0, hexpower is set to and
 *    impossible value, and the function returns 0.
\*--------------------------------------------------------------------------*/

int text2fci( const char *text, unsigned char *hexdigit, unsigned char *hexpower)
{
   typedef struct
     {
	const char *ptext;		/* pmr: const */
	unsigned char hexdigit;
	unsigned char hexpower;
	unsigned char padding[6];	/* pmr: padding to align */
     }
   TextLookupTable;
   /* This defines the various font control commands and the corresponding
    * hexdigit and hexpower in the FCI.
    */
#define N_TextLookupTable 10
   const TextLookupTable lookup[N_TextLookupTable] = {
	{"<sans-serif/>", PL_FCI_SANS, PL_FCI_FAMILY, "     "},
	{"<serif/>", PL_FCI_SERIF, PL_FCI_FAMILY, "     "},
	{"<monospace/>", PL_FCI_MONO, PL_FCI_FAMILY, "     "},
	{"<script/>", PL_FCI_SCRIPT, PL_FCI_FAMILY, "     "},
	{"<symbol/>", PL_FCI_SYMBOL, PL_FCI_FAMILY, "     "},
	{"<upright/>", PL_FCI_UPRIGHT, PL_FCI_STYLE, "     "},
	{"<italic/>", PL_FCI_ITALIC, PL_FCI_STYLE, "     "},
	{"<oblique/>", PL_FCI_OBLIQUE, PL_FCI_STYLE, "     "},
	{"<medium/>", PL_FCI_MEDIUM, PL_FCI_WEIGHT, "     "},
	{"<bold/>", PL_FCI_BOLD, PL_FCI_WEIGHT, "     "}
   };
   int i, length;
   for (i=0; i<N_TextLookupTable; i++) {
      length = strlen(lookup[i].ptext);
      if (! strncmp(text, lookup[i].ptext, length)) {
	 *hexdigit = lookup[i].hexdigit;
	 *hexpower = lookup[i].hexpower;
	 return(length);
      }
   }
   *hexdigit = 0;
   *hexpower = PL_FCI_HEXPOWER_IMPOSSIBLE;
   return(0);
}

PLUNICODE unicode_buffer[1024];

void
plP_text(PLINT base, PLFLT just, PLFLT *xform, PLINT x, PLINT y,
	 PLINT refx, PLINT refy, const char *string)
{

   if (plsc->dev_text) { /* Does the device render it's own text ? */
      EscText args;
      short len=0;
      char skip;
      unsigned short i,j;
      PLUNICODE code;
      unsigned char esc;
      int idx;

      args.base = base;
      args.just = just;
      args.xform = xform;
      args.x = x;
      args.y = y;
      args.refx = refx;
      args.refy = refy;
      args.string = string;

      if (plsc->dev_unicode) { /* Does the device also understand unicode? */
	 PLINT ig;
	 PLUNICODE fci, fcisave;
	 unsigned char hexdigit, hexpower;

	 /* Now process the text string */

	 if (string!=NULL) {        /* If the string isn't blank, then we will
                                     * continue
				     */

	    len=strlen(string);     /* this length is only used in the loop
				     * counter, we will work out the length of
				     * the unicode string as we go */
	    plgesc(&esc);
	
	    /* At this stage we will do some translations into unicode, like
	     * conversion to Greek , and will save other translations such as
	     * superscript for the driver to do later on. As we move through
	     * the string and do the translations, we will get
	     * rid of the esc character sequence, just replacing it with
	     * unicode.
	     */
	
	    /* Obtain FCI (font characterization integer) for start of
	     * string. */
	    plgfci(&fci);
	    for (j=i=0;i<len;i++) {    /* Walk through the string, and convert
					* some stuff to unicode on the fly */
	       skip=0;
	
	       if (string[i]==esc) {
		  switch(string[i+1]) {
		   case '(':  /* hershey code */
		     i+=2+text2num(&string[i+2],')',&code);
		     idx=plhershey2unicode(code);
		     /* momentarily switch to symbol font. */
		     fcisave = fci;
		     plP_hex2fci(PL_FCI_SYMBOL, PL_FCI_FAMILY, &fci);
		     unicode_buffer[j++]= fci;
		     unicode_buffer[j++] = \
		       (PLUNICODE)hershey_to_unicode_lookup_table[idx].Unicode;

		     /* if unicode_buffer[j-1] corresponds to the escape
		      * character must unescape it by appending one more.
		      * This will probably always be necessary since it is
		      * likely unicode_buffer will always have to contain
		      * escape characters that are interpreted by the device
		      * driver.
		      */
		     if (unicode_buffer[j-1]==esc) unicode_buffer[j++]=esc;
		     fci = fcisave;
		     unicode_buffer[j]= fci;
		     skip=1;
		     break;
		
		   case '[':  /* unicode */
		     i+=2+text2num(&string[i+2],']',&code);
		     /* momentarily switch to symbol font. */
		     fcisave = fci;
		     plP_hex2fci(PL_FCI_SYMBOL, PL_FCI_FAMILY, &fci);
		     unicode_buffer[j++]= fci;
		     unicode_buffer[j++]=code;
		     /* if unicode_buffer[j-1] corresponds to the escape
		      * character must unescape it by appending one more.
		      * This will probably always be necessary since it is
		      * likely unicode_buffer will always have to contain
		      * escape characters that are interpreted by the device
		      * driver.
		      */
		     if (unicode_buffer[j-1]==esc) unicode_buffer[j++]=esc;
		     fci = fcisave;
		     unicode_buffer[j] = fci;
		     skip=1;
		     break;
		
		   case '<':  /* change font*/
		     if ('0' <= string[i+2] && string[i+2] <= '9' ) {
			i+=2+text2num(&string[i+2],'>', &code);
			if (code & PL_FCI_MARK) {
			   /* code is a complete FCI (font characterization
			    * integer): change FCI to this value.
			    */
			   fci = code;
			   unicode_buffer[j]=fci;
			   skip=1;
			}
			else {
			   /* code is not complete FCI. Change
			    * FCI with hex power in rightmost hex
			    * digit and hex digit value in second rightmost
			    * hex digit.
			    */
			   hexdigit = (code >> 4) & PL_FCI_HEXDIGIT_MASK;
			   hexpower = code & PL_FCI_HEXPOWER_MASK;
			   plP_hex2fci(hexdigit, hexpower, &fci);
			   unicode_buffer[j]=fci;
			   skip=1;
			}
		     }
		
		     else {
			i+=text2fci(&string[i+1], &hexdigit, &hexpower);
			if (hexpower < 7) {
			   plP_hex2fci(hexdigit, hexpower, &fci);
			   unicode_buffer[j]=fci;
			   skip=1;
			}
		     }
		     break;
		
		   case 'f':  /* Deprecated Hershey-style font change*/
		   case 'F':  /* Deprecated Hershey-style font change*/
		     /* We implement an approximate response here so that
		      * reasonable results are obtained for unicode fonts,
		      * but this method is deprecated and the #<nnn> or
		      * #<command string> methods should be used instead
		      * to change unicode fonts in mid-string.
		      */
		     fci = PL_FCI_MARK;
		     if (string[i+2] == 'n') {
			/* medium, upright, sans-serif */
			plP_hex2fci(PL_FCI_SANS, PL_FCI_FAMILY, &fci);
		     } else if (string[i+2] == 'r') {
			/* medium, upright, serif */
			plP_hex2fci(PL_FCI_SERIF, PL_FCI_FAMILY, &fci);
		     } else if (string[i+2] == 'i') {
			/* medium, italic, serif */
			plP_hex2fci(PL_FCI_ITALIC, PL_FCI_STYLE, &fci);
			plP_hex2fci(PL_FCI_SERIF, PL_FCI_FAMILY, &fci);
		     } else if (string[i+2] == 's') {
			/* medium, upright, script */
			plP_hex2fci(PL_FCI_SCRIPT, PL_FCI_FAMILY, &fci);
		     } else
		       fci = PL_FCI_IMPOSSIBLE;
		
		     if (fci != PL_FCI_IMPOSSIBLE){
			i+=2;
			unicode_buffer[j] = fci;
			skip = 1;
		     }
		     break;
		
		   case 'g':  /* Greek font */
		   case 'G':  /* Greek font */
		     /* Get the index in the lookup table
		      * 527 = upper case alpha displacement in Hershey Table
		      * 627 = lower case alpha displacement in Hershey Table
		      */
		     /* momentarily switch to symbol font. */
		     fcisave = fci;
		     plP_hex2fci(PL_FCI_SYMBOL, PL_FCI_FAMILY, &fci);
		     unicode_buffer[j++]= fci;
		     ig = plP_strpos(plP_greek_mnemonic, string[i+2]);
		     if (ig >= 0) {
			if (ig >= 24)
			  ig = ig + 100 - 24;
			idx=plhershey2unicode(ig+527);
			unicode_buffer[j++] = \
			  (PLUNICODE)hershey_to_unicode_lookup_table[idx].Unicode;
			i+=2;
			skip=1;  /* skip is set if we have copied something
				  * into the unicode table */
		     }
		     else {
			/* Use "unknown" unicode character if string[i+2]
			 * is not in the Greek array.*/
			unicode_buffer[j++]=(PLUNICODE)0x00;
			i+=2;
			skip=1;  /* skip is set if we have copied something
				  * into  the unicode table */
		     }
		     fci = fcisave;
		     unicode_buffer[j]= fci;
		     break;
		
		  }
	       }
	
	       if (skip==0) {
                  PLUNICODE unichar = 0;
#ifdef HAVE_LIBUNICODE
		  char* ptr = unicode_get_utf8 (string + i, &unichar);
#else
		  const char* ptr = utf8_to_ucs4 (string + i, &unichar);
#endif
                  if (ptr == NULL) {
                    char buf[80];
                    strncpy (buf, string, 30);
                    sprintf (buf, "UTF-8 string is malformed: %s%s",
                             buf, strlen (string) > 30 ? "[...]" : "");
                    plabort (buf);
                  }
                  unicode_buffer [j] = unichar;
                  i += ptr - (string + i) - 1;

		  /* Search for escesc (an unescaped escape) in the input
		   * string and adjust unicode_buffer accordingly).
		   */
		  if (unicode_buffer[j] == esc && string[i+1] == esc) {
		    i++;
		    unicode_buffer[++j] = esc;
		  }
	       }
	       j++;
	    }
	    if (j > 0) {
	       args.unicode_array_len=j; /* Much easier to set the length than
					  * work it out later :-) */
	       args.unicode_array=&unicode_buffer[0]; /* Get address of the
						       * unicode buffer (even
						       * though it is
						       * currently  static) */
	    } else
	      /* Don't print anything, if there is no unicode to print! */
	      return;
	 }
      }

      if (plsc->dev_unicode) {
	args.string=NULL; /* We are using unicode */
      }
      else  {
	args.string = string;
      }

      plP_esc(PLESC_HAS_TEXT, &args);
#ifndef DEBUG_TEXT
   } else {
#endif
      plstr(base, xform, refx, refy, string);
   }
}

/* convert utf8 string to ucs4 unichar */
static const char *
utf8_to_ucs4(const char *ptr, PLUNICODE *unichar)
{
   char tmp;
   int isFirst = 1;
   int cnt = 0;

   do {
      /* Get next character in string */
      tmp = *ptr++;
      if (isFirst) { /* First char in UTF8 sequence */
	 isFirst = 0;
	 /* Determine length of sequence */
	 if ((unsigned char)(tmp & 0x80) == 0x00) { /* single char */
	    *unichar = (unsigned int)tmp & 0x7F;
	    cnt = 0;
	 } else if ((unsigned char)(tmp & 0xE0) == 0xC0) { /* 2 chars */
	    *unichar = (unsigned int)tmp & 0x1F;
	    cnt = 1;
	 } else if ((unsigned char)(tmp & 0xF0) == 0xE0) { /* 3 chars */
	    *unichar = (unsigned char)tmp & 0x0F;
	    cnt = 2;
	 } else if ((unsigned char)(tmp & 0xF8) == 0xF0) { /* 4 chars */
	    *unichar = (unsigned char)tmp & 0x07;
	    cnt = 3;
	 } else if ((unsigned char)(tmp & 0xFC) == 0xF8) { /* 5 chars */
	    *unichar = (unsigned char)tmp & 0x03;
	    cnt = 4;
	 } else if ((unsigned char)(tmp & 0xFE) == 0xFC) { /* 6 chars */
	    *unichar = (unsigned char)tmp & 0x01;
	    cnt = 5;
	 } else { /* Malformed */
	    ptr = NULL;
	    cnt = 0;
	 }
      } else { /* Subsequent char in UTF8 sequence */
	 if ((unsigned char)(tmp & 0xC0) == 0x80) {
	    *unichar = (*unichar << 6) | ((unsigned int)tmp & 0x3F);
	    cnt--;
	 } else { /* Malformed */
	    ptr = NULL;
	    cnt = 0;
	 }
      }
   } while (cnt > 0);
   return (const char *) ptr;
}

/* convert ucs4 unichar to utf8 string */
int
ucs4_to_utf8(PLUNICODE unichar, char *ptr)
{
  unsigned char *tmp;
  int len;

  tmp = (unsigned char *)ptr;

  if ( (unichar & 0xffff80) == 0 ) {  /* single byte */
    *tmp = (unsigned char) unichar;
    tmp++;
    len = 1;
  }
  else if ( (unichar & 0xfff800) == 0) { /* two bytes */
    *tmp = (unsigned char) 0xc0 | (unichar >> 6);
    tmp++;
    *tmp = (unsigned char) 0x80 | (unichar & 0x3f);
    tmp++;
    len = 2;
  }
  else if ( (unichar & 0xff0000) == 0) { /* three bytes */
    *tmp = (unsigned char) 0xe0 | (unichar >> 12);
    tmp++;
    *tmp = (unsigned char) 0x80 | ((unichar >> 6) & 0x3f);
    tmp++;
    *tmp = (unsigned char) 0x80 | (unichar & 0x3f);
    tmp++;
    len = 3;
  }
  else if ( (unichar & 0xe0000) == 0){ /* four bytes */
    *tmp = (unsigned char) 0xf0 | (unichar >> 18);
    tmp++;
    *tmp = (unsigned char) 0x80 | ((unichar >> 12) & 0x3f);
    tmp++;
    *tmp = (unsigned char) 0x80 | ((unichar >> 6) & 0x3f);
    tmp++;
    *tmp = (unsigned char) 0x80 | (unichar & 0x3f);
    tmp++;
    len = 4;
  }
  else {  /* Illegal coding */
    len = 0;
  }
  *tmp = '\0';

  return len;
}

static void
grline(short *x, short *y, PLINT npts)
{
    (void) npts; 			/* pmr: make it used */
   (*plsc->dispatch_table->pl_line) ( (struct PLStream_struct *) plsc,
				      x[0], y[0], x[1], y[1] );
}

static void
grpolyline(short *x, short *y, PLINT npts)
{
   (*plsc->dispatch_table->pl_polyline) ( (struct PLStream_struct *) plsc,
					  x, y, npts );
}

static void
grfill(short *x, short *y, PLINT npts)
{
   plsc->dev_npts = npts;
   plsc->dev_x = x;
   plsc->dev_y = y;

   (*plsc->dispatch_table->pl_esc) ( (struct PLStream_struct *) plsc,
				     PLESC_FILL, NULL );
}

/*--------------------------------------------------------------------------*\
 * void difilt
 *
 * Driver interface filter -- passes all coordinates through a variety
 * of filters.  These include filters to change :
 *
 *	- mapping of meta to physical coordinates
 *	- plot orientation
 *	- window into plot (zooms)
 *	- window into device (i.e set margins)
 *
 * The filters are applied in the order specified above.  Because the
 * orientation change comes first, subsequent window specifications affect
 * the new coordinates (i.e. after a 90 degree flip, what was x is now y).
 * This is the only way that makes sense from a graphical interface
 * (e.g. TCL/TK driver).
 *
 * Where appropriate, the page clip limits are modified.
\*--------------------------------------------------------------------------*/

void
difilt(PLINT *myxscl, PLINT *myyscl, PLINT npts,
       PLINT *clpxmi, PLINT *clpxma, PLINT *clpymi, PLINT *clpyma)
{
    PLINT i, x, y;

/* Map meta coordinates to physical coordinates */

    if (plsc->difilt & PLDI_MAP) {
	for (i = 0; i < npts; i++) {
	    myxscl[i] = plsc->dimxax * myxscl[i] + plsc->dimxb;
	    myyscl[i] = plsc->dimyay * myyscl[i] + plsc->dimyb;
	}
    }

/* Change orientation */

    if (plsc->difilt & PLDI_ORI) {
	for (i = 0; i < npts; i++) {
	    x = plsc->dioxax * myxscl[i] + plsc->dioxay * myyscl[i] +
		plsc->dioxb;
	    y = plsc->dioyax * myxscl[i] + plsc->dioyay * myyscl[i] +
		plsc->dioyb;
	    myxscl[i] = x;
	    myyscl[i] = y;
	}
    }

/* Change window into plot space */

    if (plsc->difilt & PLDI_PLT) {
	for (i = 0; i < npts; i++) {
	    myxscl[i] = plsc->dipxax * myxscl[i] + plsc->dipxb;
	    myyscl[i] = plsc->dipyay * myyscl[i] + plsc->dipyb;
	}
    }

/* Change window into device space and set clip limits */
/* (this is the only filter that modifies them) */

    if (plsc->difilt & PLDI_DEV) {
	for (i = 0; i < npts; i++) {
	    myxscl[i] = plsc->didxax * myxscl[i] + plsc->didxb;
	    myyscl[i] = plsc->didyay * myyscl[i] + plsc->didyb;
	}
	*clpxmi = plsc->diclpxmi;
	*clpxma = plsc->diclpxma;
	*clpymi = plsc->diclpymi;
	*clpyma = plsc->diclpyma;
    }
    else {
      *clpxmi = plsc->phyxmi;
      *clpxma = plsc->phyxma;
      *clpymi = plsc->phyymi;
      *clpyma = plsc->phyyma;
    }
}

static void
sdifilt(short *myxscl, short *myyscl, PLINT npts,
       PLINT *clpxmi, PLINT *clpxma, PLINT *clpymi, PLINT *clpyma)
{
  int i;
  short x, y;

/* Map meta coordinates to physical coordinates */

    if (plsc->difilt & PLDI_MAP) {
    for (i = 0; i < npts; i++) {
        myxscl[i] = plsc->dimxax * myxscl[i] + plsc->dimxb;
        myyscl[i] = plsc->dimyay * myyscl[i] + plsc->dimyb;
    }
    }

/* Change orientation */

    if (plsc->difilt & PLDI_ORI) {
    for (i = 0; i < npts; i++) {
        x = plsc->dioxax * myxscl[i] + plsc->dioxay * myyscl[i] + plsc->dioxb;
        y = plsc->dioyax * myxscl[i] + plsc->dioyay * myyscl[i] + plsc->dioyb;
        myxscl[i] = x;
        myyscl[i] = y;
    }
    }

/* Change window into plot space */

    if (plsc->difilt & PLDI_PLT) {
    for (i = 0; i < npts; i++) {
        myxscl[i] = plsc->dipxax * myxscl[i] + plsc->dipxb;
        myyscl[i] = plsc->dipyay * myyscl[i] + plsc->dipyb;
    }
    }

/* Change window into device space and set clip limits */
/* (this is the only filter that modifies them) */

    if (plsc->difilt & PLDI_DEV) {
    for (i = 0; i < npts; i++) {
        myxscl[i] = plsc->didxax * myxscl[i] + plsc->didxb;
        myyscl[i] = plsc->didyay * myyscl[i] + plsc->didyb;
    }
    *clpxmi = plsc->diclpxmi;
    *clpxma = plsc->diclpxma;
    *clpymi = plsc->diclpymi;
    *clpyma = plsc->diclpyma;
    }
    else {
    *clpxmi = plsc->phyxmi;
    *clpxma = plsc->phyxma;
    *clpymi = plsc->phyymi;
    *clpyma = plsc->phyyma;
    }
}

/*--------------------------------------------------------------------------*\
 * void pldi_ini
 *
 * Updates driver interface, making sure everything is in order.
 * Even if filter is not being used, the defaults need to be set up.
\*--------------------------------------------------------------------------*/

static void
setdef_diplt(void)			/* pmr: fix prototype */
{
    plsc->dipxmin = 0.0;
    plsc->dipxmax = 1.0;
    plsc->dipymin = 0.0;
    plsc->dipymax = 1.0;
}

static void			/* pmr: fix prototype */
setdef_didev(void)
{
    plsc->mar = 0.0;
    plsc->aspect = 0.0;
    plsc->jx = 0.0;
    plsc->jy = 0.0;
}

static void
setdef_diori(void)			/* pmr: fix prototype */
{
    plsc->diorot = 0.;
}

static void
pldi_ini(void)
{
    if (plsc->level >= 1) {
	if (plsc->difilt & PLDI_MAP)	/* Coordinate mapping */
	    calc_dimap();

	if (plsc->difilt & PLDI_ORI)	/* Orientation */
	    calc_diori();
	else
	    setdef_diori();

	if (plsc->difilt & PLDI_PLT) 	/* Plot window */
	    calc_diplt();
	else
	    setdef_diplt();

	if (plsc->difilt & PLDI_DEV)	/* Device window */
	    calc_didev();
	else
	    setdef_didev();
    }
}

/*--------------------------------------------------------------------------*\
 * void pldid2pc
 *
 * Converts input values from relative device coordinates to relative plot
 * coordinates.  This function must be called when selecting a plot window
 * from a display driver, since the coordinates chosen by the user are
 * necessarily device-specific.
\*--------------------------------------------------------------------------*/

void
pldid2pc(PLFLT *xmin, PLFLT *ymin, PLFLT *xmax, PLFLT *ymax)
{
    PLFLT pxmin, pymin, pxmax, pymax;
    PLFLT sxmin, symin, sxmax, symax;
    PLFLT rxmin, rymin, rxmax, rymax;

    if (plsc->difilt & PLDI_DEV) {

	pldebug("pldid2pc",
		"Relative device coordinates (in): %f, %f, %f, %f\n",
		*xmin, *ymin, *xmax, *ymax);

	pxmin = plP_dcpcx(*xmin);
	pymin = plP_dcpcy(*ymin);
	pxmax = plP_dcpcx(*xmax);
	pymax = plP_dcpcy(*ymax);

	sxmin = (pxmin - plsc->didxb) / plsc->didxax;
	symin = (pymin - plsc->didyb) / plsc->didyay;
	sxmax = (pxmax - plsc->didxb) / plsc->didxax;
	symax = (pymax - plsc->didyb) / plsc->didyay;

	rxmin = plP_pcdcx(sxmin);
	rymin = plP_pcdcy(symin);
	rxmax = plP_pcdcx(sxmax);
	rymax = plP_pcdcy(symax);

	*xmin = (rxmin < 0) ? 0 : rxmin;
	*xmax = (rxmax > 1) ? 1 : rxmax;
	*ymin = (rymin < 0) ? 0 : rymin;
	*ymax = (rymax > 1) ? 1 : rymax;

	pldebug("pldid2pc",
		"Relative plot coordinates (out): %f, %f, %f, %f\n",
		rxmin, rymin, rxmax, rymax);
    }
}

/*--------------------------------------------------------------------------*\
 * void pldip2dc
 *
 * Converts input values from relative plot coordinates to relative
 * device coordinates.
\*--------------------------------------------------------------------------*/

void
pldip2dc(PLFLT *xmin, PLFLT *ymin, PLFLT *xmax, PLFLT *ymax)
{
    PLFLT pxmin, pymin, pxmax, pymax;
    PLFLT sxmin, symin, sxmax, symax;
    PLFLT rxmin, rymin, rxmax, rymax;

    if (plsc->difilt & PLDI_DEV) {

	pldebug("pldip2pc",
		"Relative plot coordinates (in): %f, %f, %f, %f\n",
		*xmin, *ymin, *xmax, *ymax);

	pxmin = plP_dcpcx(*xmin);
	pymin = plP_dcpcy(*ymin);
	pxmax = plP_dcpcx(*xmax);
	pymax = plP_dcpcy(*ymax);

	sxmin = pxmin * plsc->didxax + plsc->didxb;
	symin = pymin * plsc->didyay + plsc->didyb;
	sxmax = pxmax * plsc->didxax + plsc->didxb;
	symax = pymax * plsc->didyay + plsc->didyb;

	rxmin = plP_pcdcx(sxmin);
	rymin = plP_pcdcy(symin);
	rxmax = plP_pcdcx(sxmax);
	rymax = plP_pcdcy(symax);

	*xmin = (rxmin < 0) ? 0 : rxmin;
	*xmax = (rxmax > 1) ? 1 : rxmax;
	*ymin = (rymin < 0) ? 0 : rymin;
	*ymax = (rymax > 1) ? 1 : rymax;

	pldebug("pldip2pc",
		"Relative device coordinates (out): %f, %f, %f, %f\n",
		rxmin, rymin, rxmax, rymax);
    }
}

/*--------------------------------------------------------------------------*\
 * void plsdiplt
 *
 * Set window into plot space
\*--------------------------------------------------------------------------*/

void
c_plsdiplt(PLFLT xmin, PLFLT ymin, PLFLT xmax, PLFLT ymax)
{
    plsc->dipxmin = (xmin < xmax) ? xmin : xmax;
    plsc->dipxmax = (xmin < xmax) ? xmax : xmin;
    plsc->dipymin = (ymin < ymax) ? ymin : ymax;
    plsc->dipymax = (ymin < ymax) ? ymax : ymin;

    if (xmin == 0. && xmax == 1. && ymin == 0. && ymax == 1.)  {
	plsc->difilt &= ~PLDI_PLT;
	return;
    }

    plsc->difilt |= PLDI_PLT;
    pldi_ini();
}

/*--------------------------------------------------------------------------*\
 * void plsdiplz
 *
 * Set window into plot space incrementally (zoom)
\*--------------------------------------------------------------------------*/

void
c_plsdiplz(PLFLT xmin, PLFLT ymin, PLFLT xmax, PLFLT ymax)
{
    if (plsc->difilt & PLDI_PLT) {
	xmin = plsc->dipxmin + (plsc->dipxmax - plsc->dipxmin) * xmin;
	ymin = plsc->dipymin + (plsc->dipymax - plsc->dipymin) * ymin;
	xmax = plsc->dipxmin + (plsc->dipxmax - plsc->dipxmin) * xmax;
	ymax = plsc->dipymin + (plsc->dipymax - plsc->dipymin) * ymax;
    }

    plsdiplt(xmin, ymin, xmax, ymax);
}

/*--------------------------------------------------------------------------*\
 * void calc_diplt
 *
 * Calculate transformation coefficients to set window into plot space.
 *
 * Note: if driver has requested to handle these commands itself, we must
 * send the appropriate escape command.  If the driver succeeds it will
 * cancel the filter operation.  The command is deferred until this point
 * to ensure that the driver has been initialized.
\*--------------------------------------------------------------------------*/

static void
calc_diplt(void)
{
    PLINT pxmin, pxmax, pymin, pymax, pxlen, pylen;

    if (plsc->dev_di) {
	(*plsc->dispatch_table->pl_esc) ( (struct PLStream_struct *) plsc,
                                          PLESC_DI, NULL );
    }

    if ( ! (plsc->difilt & PLDI_PLT))
	return;

    pxmin = plP_dcpcx(plsc->dipxmin);
    pxmax = plP_dcpcx(plsc->dipxmax);
    pymin = plP_dcpcy(plsc->dipymin);
    pymax = plP_dcpcy(plsc->dipymax);

    pxlen = pxmax - pxmin;
    pylen = pymax - pymin;
    pxlen = MAX(1, pxlen);
    pylen = MAX(1, pylen);

    plsc->dipxax = plsc->phyxlen / (double) pxlen;
    plsc->dipyay = plsc->phyylen / (double) pylen;
    plsc->dipxb = plsc->phyxmi - plsc->dipxax * pxmin;
    plsc->dipyb = plsc->phyymi - plsc->dipyay * pymin;
}

/*--------------------------------------------------------------------------*\
 * void plgdiplt
 *
 * Retrieve current window into plot space
\*--------------------------------------------------------------------------*/

void
c_plgdiplt(PLFLT *p_xmin, PLFLT *p_ymin, PLFLT *p_xmax, PLFLT *p_ymax)
{
    *p_xmin = plsc->dipxmin;
    *p_xmax = plsc->dipxmax;
    *p_ymin = plsc->dipymin;
    *p_ymax = plsc->dipymax;
}

/*--------------------------------------------------------------------------*\
 * void plsdidev
 *
 * Set window into device space using margin, aspect ratio, and
 * justification.  If you want to just use the previous value for any of
 * these, just pass in the magic value PL_NOTSET.
 *
 * It is unlikely that one should ever need to change the aspect ratio
 * but it's in there for completeness.
\*--------------------------------------------------------------------------*/

void
c_plsdidev(PLFLT mar, PLFLT aspect, PLFLT jx, PLFLT jy)
{
    plsetvar(plsc->mar, mar);
    plsetvar(plsc->aspect, aspect);
    plsetvar(plsc->jx, jx);
    plsetvar(plsc->jy, jy);

    if (mar == 0. && aspect == 0. && jx == 0. && jy == 0. &&
	! (plsc->difilt & PLDI_ORI)) {
	plsc->difilt &= ~PLDI_DEV;
	return;
    }

    plsc->difilt |= PLDI_DEV;
    pldi_ini();
}

/*--------------------------------------------------------------------------*\
 * void calc_didev
 *
 * Calculate transformation coefficients to set window into device space.
 * Calculates relative window bounds and calls plsdidxy to finish the job.
\*--------------------------------------------------------------------------*/

static void
calc_didev(void)
{
    PLFLT lx, ly, aspect, aspdev;
    PLFLT xmin, xmax, xlen, ymin, ymax, ylen;
    PLINT pxmin, pxmax, pymin, pymax, pxlen, pylen;

    if (plsc->dev_di) {
	(*plsc->dispatch_table->pl_esc) ( (struct PLStream_struct *) plsc,
                                          PLESC_DI, NULL );
    }

    if ( ! (plsc->difilt & PLDI_DEV))
	return;

/* Calculate aspect ratio of physical device */

    lx = plsc->phyxlen / plsc->xpmm;
    ly = plsc->phyylen / plsc->ypmm;
    aspdev = lx / ly;

    if (plsc->difilt & PLDI_ORI)
	aspect = plsc->aspori;
    else
	aspect = plsc->aspect;

    if (aspect <= 0.)
	aspect = plsc->aspdev;

/* Failsafe */

    plsc->mar = (plsc->mar > 0.5) ? 0.5 : plsc->mar;
    plsc->mar = (plsc->mar < 0.0) ? 0.0 : plsc->mar;
    plsc->jx = (plsc->jx >  0.5) ?  0.5 : plsc->jx;
    plsc->jx = (plsc->jx < -0.5) ? -0.5 : plsc->jx;
    plsc->jy = (plsc->jy >  0.5) ?  0.5 : plsc->jy;
    plsc->jy = (plsc->jy < -0.5) ? -0.5 : plsc->jy;

/* Relative device coordinates that neutralize aspect ratio difference */

    xlen = (aspect < aspdev) ? (aspect / aspdev) : 1.0;
    ylen = (aspect < aspdev) ? 1.0 : (aspdev / aspect);

    xlen *= (1.0 - 2.*plsc->mar);
    ylen *= (1.0 - 2.*plsc->mar);

    xmin = (1. - xlen) * (0.5 + plsc->jx);
    xmax = xmin + xlen;

    ymin = (1. - ylen) * (0.5 + plsc->jy);
    ymax = ymin + ylen;

/* Calculate transformation coefficients */

    pxmin = plP_dcpcx(xmin);
    pxmax = plP_dcpcx(xmax);
    pymin = plP_dcpcy(ymin);
    pymax = plP_dcpcy(ymax);

    pxlen = pxmax - pxmin;
    pylen = pymax - pymin;
    pxlen = MAX(1, pxlen);
    pylen = MAX(1, pylen);

    plsc->didxax = pxlen / (double) plsc->phyxlen;
    plsc->didyay = pylen / (double) plsc->phyylen;
    plsc->didxb = pxmin - plsc->didxax * plsc->phyxmi;
    plsc->didyb = pymin - plsc->didyay * plsc->phyymi;

/* Set clip limits to conform to new page size */

    plsc->diclpxmi = plsc->didxax * plsc->phyxmi + plsc->didxb;
    plsc->diclpxma = plsc->didxax * plsc->phyxma + plsc->didxb;
    plsc->diclpymi = plsc->didyay * plsc->phyymi + plsc->didyb;
    plsc->diclpyma = plsc->didyay * plsc->phyyma + plsc->didyb;
}

/*--------------------------------------------------------------------------*\
 * void plgdidev
 *
 * Retrieve current window into device space
\*--------------------------------------------------------------------------*/

void
c_plgdidev(PLFLT *p_mar, PLFLT *p_aspect, PLFLT *p_jx, PLFLT *p_jy)
{
    *p_mar = plsc->mar;
    *p_aspect = plsc->aspect;
    *p_jx = plsc->jx;
    *p_jy = plsc->jy;
}

/*--------------------------------------------------------------------------*\
 * void plsdiori
 *
 * Set plot orientation, specifying rotation in units of pi/2.
\*--------------------------------------------------------------------------*/

void
c_plsdiori(PLFLT rot)
{
    plsc->diorot = rot;
    if (rot == 0.) {
	plsc->difilt &= ~PLDI_ORI;
	pldi_ini();
	return;
    }

    plsc->difilt |= PLDI_ORI;
    pldi_ini();
}

/*--------------------------------------------------------------------------*\
 * void calc_diori
 *
 * Calculate transformation coefficients to arbitrarily orient plot.
 * Preserve aspect ratios so the output doesn't suck.
\*--------------------------------------------------------------------------*/

static void
calc_diori(void)
{
    PLFLT r11, r21, r12, r22, cost, sint;
    PLFLT xx0, yy0, lx, ly, aspect;

    if (plsc->dev_di) {
	(*plsc->dispatch_table->pl_esc) ( (struct PLStream_struct *) plsc,
                                          PLESC_DI, NULL );
    }

    if ( ! (plsc->difilt & PLDI_ORI))
	return;

/* Center point of rotation */

    xx0 = (plsc->phyxma + plsc->phyxmi) / 2.;
    yy0 = (plsc->phyyma + plsc->phyymi) / 2.;

/* Rotation matrix */

    r11 = cos(plsc->diorot * PI / 2.);
    r21 = sin(plsc->diorot * PI / 2.);
    r12 = -r21;
    r22 = r11;

    cost = ABS(r11);
    sint = ABS(r21);

/* Flip aspect ratio as necessary.  Grungy but I don't see a better way */

    aspect = plsc->aspect;
    if (aspect == 0.)
	aspect = plsc->aspdev;

    if (plsc->freeaspect)
	plsc->aspori = aspect;
    else
	plsc->aspori = (aspect * cost + sint) / (aspect * sint + cost);

    if ( ! (plsc->difilt & PLDI_DEV)) {
	plsc->difilt |= PLDI_DEV;
	setdef_didev();
    }
    calc_didev();

/* Compute scale factors */

    lx = plsc->phyxlen;
    ly = plsc->phyylen;

/* Transformation coefficients */

    plsc->dioxax = r11;
    plsc->dioxay = r21 * (lx / ly);
    plsc->dioxb = (1. - r11) * xx0 - r21 * yy0 * (lx / ly);

    plsc->dioyax = r12 * (ly / lx);
    plsc->dioyay = r22;
    plsc->dioyb = (1. - r22) * yy0 - r12 * xx0 * (ly / lx);
}

/*--------------------------------------------------------------------------*\
 * void plgdiori
 *
 * Get plot orientation
\*--------------------------------------------------------------------------*/

void
c_plgdiori(PLFLT *p_rot)
{
    *p_rot = plsc->diorot;
}

/*--------------------------------------------------------------------------*\
 * void plsdimap
 *
 * Set up transformation from metafile coordinates.  The size of the plot is
 * scaled so as to preserve aspect ratio.  This isn't intended to be a
 * general-purpose facility just yet (not sure why the user would need it,
 * for one).
\*--------------------------------------------------------------------------*/

void
c_plsdimap(PLINT dimxmin, PLINT dimxmax, PLINT dimymin, PLINT dimymax,
	   PLFLT dimxpmm, PLFLT dimypmm)
{
    plsetvar(plsc->dimxmin, dimxmin);
    plsetvar(plsc->dimxmax, dimxmax);
    plsetvar(plsc->dimymin, dimymin);
    plsetvar(plsc->dimymax, dimymax);
    plsetvar(plsc->dimxpmm, dimxpmm);
    plsetvar(plsc->dimypmm, dimypmm);

    plsc->difilt |= PLDI_MAP;
    pldi_ini();
}

/*--------------------------------------------------------------------------*\
 * void calc_dimap
 *
 * Set up transformation from metafile coordinates.  The size of the plot is
 * scaled so as to preserve aspect ratio.  This isn't intended to be a
 * general-purpose facility just yet (not sure why the user would need it,
 * for one).
\*--------------------------------------------------------------------------*/

static void
calc_dimap(void)			/* pmr: prototype */
{
    PLFLT lx, ly;
    PLINT pxmin, pxmax, pymin, pymax;
    PLFLT dimxlen, dimylen, pxlen, pylen;

    if ((plsc->dimxmin == plsc->phyxmi) && (plsc->dimxmax == plsc->phyxma) &&
	(plsc->dimymin == plsc->phyymi) && (plsc->dimymax == plsc->phyyma) &&
	(plsc->dimxpmm == plsc->xpmm) && (plsc->dimypmm == plsc->ypmm)) {
	plsc->difilt &= ~PLDI_MAP;
	return;
    }

/* Set default aspect ratio */

    lx = (plsc->dimxmax - plsc->dimxmin + 1) / plsc->dimxpmm;
    ly = (plsc->dimymax - plsc->dimymin + 1) / plsc->dimypmm;

    plsc->aspdev = lx / ly;

/* Build transformation to correct physical coordinates */

    dimxlen = plsc->dimxmax - plsc->dimxmin;
    dimylen = plsc->dimymax - plsc->dimymin;

    pxmin = plsc->phyxmi;
    pxmax = plsc->phyxma;
    pymin = plsc->phyymi;
    pymax = plsc->phyyma;
    pxlen = pxmax - pxmin;
    pylen = pymax - pymin;

    plsc->dimxax = pxlen / dimxlen;
    plsc->dimyay = pylen / dimylen;
    plsc->dimxb = pxmin - pxlen * plsc->dimxmin / dimxlen;
    plsc->dimyb = pymin - pylen * plsc->dimymin / dimylen;
}

/*--------------------------------------------------------------------------*\
 * void plflush()
 *
 * Flushes the output stream.  Use sparingly, if at all.
\*--------------------------------------------------------------------------*/

void
c_plflush(void)
{
    if (plsc->dev_flush) {
	(*plsc->dispatch_table->pl_esc) ( (struct PLStream_struct *) plsc,
                                          PLESC_FLUSH, NULL );
    }
    else {
	if (plsc->OutFile != NULL)
	    fflush(plsc->OutFile);
    }
}

/*--------------------------------------------------------------------------*\
 * Startup routines.
\*--------------------------------------------------------------------------*/

/*--------------------------------------------------------------------------*\
 * void pllib_init()
 *
 * Initialize library.  Called internally by every startup routine.
 * Everything you want to always be initialized before plinit() is called
 * you should put here.  E.g. dispatch table setup, rcfile read, etc.
\*--------------------------------------------------------------------------*/

void
pllib_init(void)			/* pmr: prototype */
{
    if (lib_initialized) return;
    lib_initialized = 1;

#ifdef ENABLE_DYNDRIVERS
/* Create libltdl resources */
        lt_dlinit();
#endif

/* Initialize the dispatch table with the info from the static drivers table
   and the available dynamic drivers. */

    plInitDispatchTable();
}

/*--------------------------------------------------------------------------*\
 * void plstar(nx, ny)
 *
 * Initialize PLplot, passing in the windows/page settings.
\*--------------------------------------------------------------------------*/

void
c_plstar(PLINT nx, PLINT ny)
{
    pllib_init();

    if (plsc->level != 0)
	plend1();

    plssub(nx, ny);

    c_plinit();
}

/*--------------------------------------------------------------------------*\
 * void plstart(devname, nx, ny)
 *
 * Initialize PLplot, passing the device name and windows/page settings.
\*--------------------------------------------------------------------------*/

void
c_plstart(const char *devname, PLINT nx, PLINT ny)
{
    pllib_init();

    if (plsc->level != 0)
	plend1();

    plssub(nx, ny);
    plsdev(devname);

    c_plinit();
}

/*--------------------------------------------------------------------------*\
 * void plinit()
 *
 * Initializes PLplot, using preset or default options.
\*--------------------------------------------------------------------------*/

void
c_plinit(void)
{
    PLFLT def_arrow_x[6] = {-0.5, 0.5, 0.3, 0.5, 0.3, 0.5};
    PLFLT def_arrow_y[6] = {0.0, 0.0,   0.2, 0.0, -0.2, 0.0};
    PLFLT lx, ly, xpmm_loc, ypmm_loc, aspect_old, aspect_new;
    PLINT mk = 0, sp = 0, inc = 0, del = 2000;

    pllib_init();

    if (plsc->level != 0)
	plend1();

/* Set stream number */

    plsc->ipls = ipls;

/* Set up devices */

    pllib_devinit();

/* Auxiliary stream setup */

    plstrm_init();

/* Initialize device & first page */

    plP_init();
    plP_bop();
    plsc->level = 1;

/* Calculate factor such that the character aspect ratio is preserved
 * when the overall aspect ratio is changed, i.e., if portrait mode is
 * requested (only honored for subset of drivers) or if the aspect ratio
 * is specified in any way, or if a 90 deg rotation occurs with
 * -freeaspect. */

/* Case where plsc->aspect has a value.... (e.g., -a aspect on the
 * command line or 2nd parameter of plsdidev specified) */
    if (plsc->aspect > 0.) {
       lx = plsc->phyxlen / plsc->xpmm;
       ly = plsc->phyylen / plsc->ypmm;
       aspect_old = lx / ly;
       aspect_new = plsc->aspect;
       plsc->caspfactor = sqrt(aspect_old/aspect_new);
    }
/* Case of 90 deg rotations with -freeaspect (this is also how portraite
 * mode is implemented for the drivers that honor -portrait). */
    else if (plsc->freeaspect && ABS(cos(plsc->diorot * PI / 2.)) <= 1.e-5) {
       lx = plsc->phyxlen / plsc->xpmm;
       ly = plsc->phyylen / plsc->ypmm;
       aspect_old = lx / ly;
       aspect_new = ly / lx;
       plsc->caspfactor = sqrt(aspect_old/aspect_new);
    }

    else
       plsc->caspfactor = 1.;

/* Load fonts */

    plsc->cfont = 1;
    plfntld(initfont);

/* Set up subpages */

    plP_subpInit();

/* Set up number of allowed digits before switching to scientific notation */
/* The user can always change this */

    if (plsc->xdigmax == 0)
	plsc->xdigmax = 4;

    if (plsc->ydigmax == 0)
	plsc->ydigmax = 4;

    if (plsc->zdigmax == 0)
	plsc->zdigmax = 3;

/* Switch to graphics mode and set color and arrow style*/

    plgra();
    plcol(1);

    plstyl(0, &mk, &sp);
    plpat(1, &inc, &del);

    plsvect(def_arrow_x, def_arrow_y, 6, 0);

/* Set clip limits. */

    plsc->clpxmi = plsc->phyxmi;
    plsc->clpxma = plsc->phyxma;
    plsc->clpymi = plsc->phyymi;
    plsc->clpyma = plsc->phyyma;

/* Page aspect ratio. */

    lx = plsc->phyxlen / plsc->xpmm;
    ly = plsc->phyylen / plsc->ypmm;
    plsc->aspdev = lx / ly;

/* Initialize driver interface */

    pldi_ini();

/* Apply compensating factor to original xpmm and ypmm so that
 * character aspect ratio is preserved when overall aspect ratio
 * is changed.  This must appear here in the code because previous
 * code in this routine and in routines that it calls must use the original
 * values of xpmm and ypmm before the compensating factor is applied.  */

    plP_gpixmm(&xpmm_loc, &ypmm_loc);
    plP_setpxl(xpmm_loc*plsc->caspfactor, ypmm_loc/plsc->caspfactor);
}

/*--------------------------------------------------------------------------*\
 * void plend()
 *
 * End a plotting session for all open streams.
\*--------------------------------------------------------------------------*/

void
c_plend(void)
{
    PLINT i;

    if (lib_initialized == 0) return;

    for (i = PL_NSTREAMS-1; i >= 0; i--) {
	if (pls[i] != NULL) {
	    plsstrm(i);
	    c_plend1();
	}
    }
    plfontrel();
#ifdef ENABLE_DYNDRIVERS
/* Release the libltdl resources */
    lt_dlexit();
/* Free up memory allocated to the dispatch tables */
    for (i = 0; i < npldynamicdevices; i++) {
      free_mem(loadable_device_list[i].devnam);
      free_mem(loadable_device_list[i].description);
      free_mem(loadable_device_list[i].drvnam);
      free_mem(loadable_device_list[i].tag);
    }
    free_mem(loadable_device_list);
    for (i = 0; i < nloadabledrivers; i++) {
      free_mem(loadable_driver_list[i].drvnam);
    }
    free_mem(loadable_driver_list);
    for (i = nplstaticdevices; i < npldrivers; i++) {
      free_mem(dispatch_table[i]->pl_MenuStr);
      free_mem(dispatch_table[i]->pl_DevName);
      free_mem(dispatch_table[i]);
    }
#endif
    for (i = 0; i < nplstaticdevices; i++) {
      free_mem(dispatch_table[i]);
    }
    free_mem(dispatch_table);

    plP_FreeDrvOpts();

    lib_initialized = 0;
}

/*--------------------------------------------------------------------------*\
 * void plend1()
 *
 * End a plotting session for the current stream only.  After the stream is
 * ended the memory associated with the stream's PLStream data structure is
 * freed (for stream > 0), and the stream counter is set to 0 (the default).
\*--------------------------------------------------------------------------*/

void
c_plend1(void)
{
    if (plsc->level > 0) {
	plP_eop();
	plP_tidy();
	plsc->level = 0;
    }
    /* Move from plP_tidy because FileName may be set even if level == 0 */
    if (plsc->FileName)
	free_mem(plsc->FileName);

/* Free all malloc'ed stream memory */

    free_mem(plsc->cmap0);
    free_mem(plsc->cmap1);
    free_mem(plsc->plwindow);
    free_mem(plsc->geometry);
    free_mem(plsc->dev);
    free_mem(plsc->BaseName);
    free_mem(plsc->Ext);		/* pmr: added for EMBOSS */
#ifndef BUFFERED_FILE
    free_mem(plsc->plbuf_buffer);
#endif
/*    if (plsc->program) free_mem(plsc->program);*/ /* pmr: now const */
    if (plsc->server_name) free_mem(plsc->server_name);
    if (plsc->server_host) free_mem(plsc->server_host);
    if (plsc->server_port) free_mem(plsc->server_port);
    if (plsc->user) free_mem(plsc->user);
    if (plsc->plserver) free_mem(plsc->plserver);
    if (plsc->auto_path) free_mem(plsc->auto_path);

    if (plsc->arrow_x) free_mem(plsc->arrow_x);
    if (plsc->arrow_y) free_mem(plsc->arrow_y);

/* Free malloc'ed stream if not in initial stream, else clear it out */

    if (ipls > 0) {
	free_mem(plsc);
	pls[ipls] = NULL;
	plsstrm(0);
    }
    else {
	memset((char *) pls[ipls], 0, sizeof(PLStream));
    }
}

/*--------------------------------------------------------------------------*\
 * void plsstrm
 *
 * Set stream number.  If the data structure for a new stream is
 * unallocated, we allocate it here.
\*--------------------------------------------------------------------------*/

void
c_plsstrm(PLINT strm)
{
    if (strm < 0 || strm >= PL_NSTREAMS) {
	fprintf(stderr,
		"plsstrm: Illegal stream number %d, must be in [0, %d]\n",
		(int) strm, PL_NSTREAMS);
    }
    else {
	ipls = strm;
	if (pls[ipls] == NULL) {
	    pls[ipls] = (PLStream *) malloc((size_t) sizeof(PLStream));
	    if (pls[ipls] == NULL)
		plexit("plsstrm: Out of memory.");

	    memset((char *) pls[ipls], 0, sizeof(PLStream));
	}
	plsc = pls[ipls];
	plsc->ipls = ipls;
    }
}

/*--------------------------------------------------------------------------*\
 * void plgstrm
 *
 * Get current stream number.
\*--------------------------------------------------------------------------*/

void
c_plgstrm(PLINT *p_strm)
{
    *p_strm = ipls;
}

/*--------------------------------------------------------------------------*\
 * void plmkstrm
 *
 * Creates a new stream and makes it the default.  Differs from using
 * plsstrm(), in that a free stream number is found, and returned.
 *
 * Unfortunately, I /have/ to start at stream 1 and work upward, since
 * stream 0 is preallocated.  One of the BIG flaws in the PLplot API is
 * that no initial, library-opening call is required.  So stream 0 must be
 * preallocated, and there is no simple way of determining whether it is
 * already in use or not.
\*--------------------------------------------------------------------------*/

void
c_plmkstrm(PLINT *p_strm)
{
    int i;

    for (i = 1; i < PL_NSTREAMS; i++) {
	if (pls[i] == NULL)
	    break;
    }

    if (i == PL_NSTREAMS) {
	fprintf(stderr, "plmkstrm: Cannot create new stream\n");
	*p_strm = -1;
    }
    else {
	*p_strm = i;
	plsstrm(i);
    }
    plstrm_init();
}

/*--------------------------------------------------------------------------*\
 * void plstrm_init
 *
 * Does required startup initialization of a stream.  Should be called right
 * after creating one (for allocating extra memory, etc).  Users shouldn't
 * need to call this directly.
 *
 * This function can be called multiple times for a given stream, in which
 * case only the first call produces any effect.  For streams >= 1, which
 * are created dynamically, this is called by the routine that allocates
 * the stream.  Stream 0, which is preallocated, is much harder to deal with
 * because any of a number of different calls may be the first call to the
 * library.  This is handled by just calling plstrm_init() from every
 * function that might be called first.  Sucks, but it should work.
\*--------------------------------------------------------------------------*/

void
plstrm_init(void)
{
    if ( ! plsc->initialized) {
	plsc->initialized = 1;

	if (plsc->cmap0 == NULL)
	    plscmap0n(0);

	if (plsc->cmap1 == NULL)
	    plscmap1n(0);
    }

    plsc->psdoc = NULL;
}

/*--------------------------------------------------------------------------*\
 * pl_cpcolor
 *
 * Utility to copy one PLColor to another.
\*--------------------------------------------------------------------------*/

void
pl_cpcolor(PLColor *to, PLColor *from)
{
    to->r = from->r;
    to->g = from->g;
    to->b = from->b;
}

/*--------------------------------------------------------------------------*\
 * void plcpstrm
 *
 * Copies state parameters from the reference stream to the current stream.
 * Tell driver interface to map device coordinates unless flags == 1.
 *
 * This function is used for making save files of selected plots (e.g.
 * from the TK driver).  After initializing, you can get a copy of the
 * current plot to the specified device by switching to this stream and
 * issuing a plcpstrm() and a plreplot(), with calls to plbop() and
 * pleop() as appropriate.  The plot buffer must have previously been
 * enabled (done automatically by some display drivers, such as X).
\*--------------------------------------------------------------------------*/

void
c_plcpstrm(PLINT iplsr, PLINT flags)
{
    int i;
    PLStream *plsr;

    plsr = pls[iplsr];
    if (plsr == NULL) {
	fprintf(stderr, "plcpstrm: stream %d not in use\n", (int) iplsr);
	return;
    }

/* May be debugging */

    plsc->debug = plsr->debug;

/* Plot buffer -- need to copy file pointer so that plreplot() works */
/* This also prevents inadvertent writes into the plot buffer */

#ifdef BUFFERED_FILE
    plsc->plbufFile = plsr->plbufFile;
#else
    plsc->plbuf_buffer = plsr->plbuf_buffer;
    plsc->plbuf_buffer_grow = plsr->plbuf_buffer_grow;
    plsc->plbuf_buffer_size = plsr->plbuf_buffer_size;
    plsc->plbuf_top = plsr->plbuf_top;
    plsc->plbuf_readpos = plsr->plbuf_readpos;
#endif

/* Driver interface */
/* Transformation must be recalculated in current driver coordinates */

    if (plsr->difilt & PLDI_PLT)
	plsdiplt(plsr->dipxmin, plsr->dipymin, plsr->dipxmax, plsr->dipymax);

    if (plsr->difilt & PLDI_DEV)
	plsdidev(plsr->mar, plsr->aspect, plsr->jx, plsr->jy);

    if (plsr->difilt & PLDI_ORI)
	plsdiori(plsr->diorot);

/* Map device coordinates */

    if ( ! (flags & 0x01)) {
	pldebug("plcpstrm", "mapping parameters: %d %d %d %d %f %f\n",
		plsr->phyxmi, plsr->phyxma, plsr->phyymi, plsr->phyyma,
		plsr->xpmm, plsr->ypmm);
	plsdimap(plsr->phyxmi, plsr->phyxma, plsr->phyymi, plsr->phyyma,
		 plsr->xpmm, plsr->ypmm);
    }

/* current color */

    pl_cpcolor(&plsc->curcolor, &plsr->curcolor);

/* cmap 0 */

    plsc->icol0 = plsr->icol0;
    plsc->ncol0 = plsr->ncol0;
    if (plsc->cmap0 != NULL)
	free((void *) plsc->cmap0);

    plsc->cmap0 = (PLColor *) calloc(1, plsc->ncol0 * sizeof(PLColor));
    for (i = 0; i < plsc->ncol0; i++)
	pl_cpcolor(&plsc->cmap0[i], &plsr->cmap0[i]);

/* cmap 1 */

    plsc->icol1 = plsr->icol1;
    plsc->ncol1 = plsr->ncol1;
    if (plsc->cmap1 != NULL)
	free((void *) plsc->cmap1);

    plsc->cmap1 = (PLColor *) calloc(1, plsc->ncol1 * sizeof(PLColor));
    for (i = 0; i < plsc->ncol1; i++)
	pl_cpcolor(&plsc->cmap1[i], &plsr->cmap1[i]);

/* Initialize if it hasn't been done yet. */

    if (plsc->level == 0)
	plinit();
}

/*--------------------------------------------------------------------------*\
 * pllib_devinit()
 *
 * Does preliminary setup of device driver.
 *
 * This function (previously plGetDev) used to be what is now shown as
 * plSelectDev below.  However, the situation is a bit more complicated now in
 * the dynloadable drivers era.  We now have to:
 *
 * 1) Make sure the dispatch table is initialized to the union of static
 *    drivers and available dynamic drivers (done from pllib_init now).
 * 2) Allow the user to select the desired device.
 * 3) Initialize the dispatch table entries for the selected device, in the
 *    case that it is a dynloadable driver that has not yet been loaded.
 *
 * Also made non-static, in order to allow some device calls to be made prior
 * to calling plinit().  E.g. plframe needs to tell the X driver to create its
 * internal data structure during widget construction time (using the escape
 * function), but doesn't call plinit() until the plframe is actually mapped.
\*--------------------------------------------------------------------------*/

void
pllib_devinit(void)			/* pmr: prototype */
{
    if (plsc->dev_initialized) return;
    plsc->dev_initialized = 1;

    plSelectDev();

    plLoadDriver();

/* offset by one since table is zero-based, but input list is not */
    plsc->dispatch_table = dispatch_table[plsc->device - 1];
}

int PLDLLIMPEXP plInBuildTree(void)			/* pmr: prototype */
{
  static int inited = 0;
  static int inBuildTree = 0;

  if (inited == 0) {
    char currdir[256];

/* AM: getcwd has a somewhat strange status on Windows, its proper
   name is _getcwd, this is a problem in the case of DLLs, like with
   the Java bindings.
*/
#if defined(WIN32) && !defined(__BORLANDC__)
#define getcwd _getcwd
#endif

    if (getcwd(currdir, 256) == NULL) {
      pldebug("plInBuildTree():", "Not enough buffer space");
    } else if (strncmp(BUILD_DIR, currdir, strlen(BUILD_DIR)) == 0)
      inBuildTree = 1;
    inited = 1;
  }
  return inBuildTree;
}

#ifdef ENABLE_DYNDRIVERS

static char*
plGetDrvDir ()
{
    char* drvdir;

/* Get drivers directory in PLPLOT_DRV_DIR or DRV_DIR,
 *  on this order
 */

    if (plInBuildTree() == 1) {
      drvdir = BUILD_DIR "/drivers";
      pldebug("plGetDrvDir", "Using %s as the driver directory.\n", drvdir);
    } else {
      pldebug("plGetDrvDir", "Trying to read env var PLPLOT_DRV_DIR\n");
      drvdir = getenv ("PLPLOT_DRV_DIR");

      if (drvdir == NULL) {
        pldebug("plGetDrvDir",
	        "Will use drivers dir: " DRV_DIR "\n");
	drvdir = DRV_DIR;
      }
    }

    return drvdir;
}

#endif


/*--------------------------------------------------------------------------*\
 * void plInitDispatchTable()
 *
 * ...
\*--------------------------------------------------------------------------*/

static int plDispatchSequencer( const void *p1, const void *p2 )
{
    const PLDispatchTable* t1 = *(const PLDispatchTable * const *) p1;
    const PLDispatchTable* t2 = *(const PLDispatchTable * const *) p2;

/*     printf( "sorting: t1.name=%s t1.seq=%d t2.name=%s t2.seq=%d\n", */
/*             t1->pl_DevName, t1->pl_seq, t2->pl_DevName, t2->pl_seq ); */

    return t1->pl_seq - t2->pl_seq;
}

static void
plInitDispatchTable(void)		/* pmr: prototype */
{
    int n;

#ifdef ENABLE_DYNDRIVERS
    char buf[300];
    char* drvdir;
    char *devnam, *devdesc, *devtype, *driver, *tag, *seqstr;
    int seq;
    int i, j, driver_found, done=0;
    FILE *fp_drvdb = NULL;
    DIR* dp_drvdir = NULL;
    struct dirent* entry;
    /* lt_dlhandle dlhand; */

    /* Make sure driver counts are zeroed */
    npldynamicdevices = 0;
    nloadabledrivers = 0;

/* Open a temporary file in which all the plD_DEVICE_INFO_<driver> strings
   will be stored */
    fp_drvdb = tmpfile ();

/* Open the drivers directory */
    drvdir = plGetDrvDir ();
    dp_drvdir = opendir (drvdir);
    if (dp_drvdir == NULL) {
      plabort ("plInitDispatchTable: Could not open drivers directory");
      return;
    }

/* Loop over each entry in the drivers directory */

    pldebug ("plInitDispatchTable", "Scanning dyndrivers dir\n");
    while ((entry = readdir (dp_drvdir)) != NULL)
    {
        char* name = entry->d_name;
        int len = strlen (name) - 3;

            pldebug ("plInitDispatchTable",
                     "Consider file %s\n", name);

/* Only consider entries that have the ".rc" suffix */
	if ((len > 0) && (strcmp (name + len, ".rc") == 0)) {
	    char path[300];
	    char buf[300];
            FILE* fd;

/* Open the driver's info file */
            sprintf (path, "%s/%s", drvdir, name);
            fd = fopen (path, "r");
            if (fd == NULL) {
	        sprintf (buf,
                  "plInitDispatchTable: Could not open driver info file %s\n",
                  name);
	        plabort (buf);
	        return;
	    }

/* Each line in the <driver>.rc file corresponds to a specific device.
 * Write it to the drivers db file and take care of leading newline
 * character */

            pldebug ("plInitDispatchTable",
                     "Opened driver info file %s\n", name);
            while (fgets (buf, 300, fd) != NULL)
	    {
                fprintf (fp_drvdb, "%s", buf);
		if ( buf [strlen (buf) - 1] != '\n' )
		    fprintf (fp_drvdb, "\n");
                npldynamicdevices++;
	    }
	    fclose (fd);
	}
    }

/* Make sure that the temporary file containing the drivers database
 * is ready to read and close the directory handle */
    fflush (fp_drvdb);
    closedir (dp_drvdir);

#endif

/* Allocate space for the dispatch table. */
    dispatch_table = (PLDispatchTable **)
	malloc( (nplstaticdevices + npldynamicdevices) * sizeof(PLDispatchTable *) );

/* Initialize the dispatch table entries for the static devices by calling
   the dispatch table initialization function for each static device.  This
   is the same function that would be called at load time for dynamic
   drivers. */

    for( n=0; n < nplstaticdevices; n++ )
    {
        dispatch_table[n] = (PLDispatchTable *)malloc( sizeof(PLDispatchTable) );

        (*static_device_initializers[n])( dispatch_table[n] );
    }
    npldrivers = nplstaticdevices;

#ifdef ENABLE_DYNDRIVERS

/* Allocate space for the device and driver specs.  We may not use all of
 * these driver descriptors, but we obviously won't need more drivers than
 * devices... */
    loadable_device_list = malloc( npldynamicdevices * sizeof(PLLoadableDevice) );
    loadable_driver_list = malloc( npldynamicdevices * sizeof(PLLoadableDriver) );

    rewind( fp_drvdb );

    i = 0;
    done = !(i < npldynamicdevices);
    while( !done ) {
        char *p = fgets( buf, 300, fp_drvdb );

        if (p == 0) {
            done = 1;
            continue;
        }

        devnam  = strtok( buf, ":" );
        devdesc = strtok( 0, ":" );
        devtype = strtok( 0, ":" );
        driver  = strtok( 0, ":" );
        seqstr  = strtok( 0, ":" );
        tag     = strtok( 0, "\n" );

        seq     = atoi(seqstr);

        n = npldrivers++;

        dispatch_table[n] = malloc( sizeof(PLDispatchTable) );

    /* Fill in the dispatch table entries. */
        dispatch_table[n]->pl_MenuStr = plstrdup(devdesc);
        dispatch_table[n]->pl_DevName = plstrdup(devnam);
        dispatch_table[n]->pl_type = atoi(devtype);
        dispatch_table[n]->pl_seq = seq;
        dispatch_table[n]->pl_init = 0;
        dispatch_table[n]->pl_line = 0;
        dispatch_table[n]->pl_polyline = 0;
        dispatch_table[n]->pl_eop = 0;
        dispatch_table[n]->pl_bop = 0;
        dispatch_table[n]->pl_tidy = 0;
        dispatch_table[n]->pl_state = 0;
        dispatch_table[n]->pl_esc = 0;

    /* Add a record to the loadable device list */
        loadable_device_list[i].devnam = plstrdup(devnam);
        loadable_device_list[i].description = plstrdup(devdesc);
        loadable_device_list[i].drvnam = plstrdup(driver);
        loadable_device_list[i].tag = plstrdup(tag);

    /* Now see if this driver has been seen before.  If not, add a driver
     * entry for it. */
        driver_found = 0;
        for( j=0; j < nloadabledrivers; j++ )
            if (strcmp( driver, loadable_driver_list[j].drvnam) == 0)
            {
                driver_found = 1;
                break;
            }

        if (!driver_found)
        {
            loadable_driver_list[nloadabledrivers].drvnam = plstrdup(driver);
            loadable_driver_list[nloadabledrivers].dlhand = 0;
            nloadabledrivers++;
        }

        loadable_device_list[i].drvidx = j;

    /* Get ready for next loadable device spec */
        i++;
    }

/* RML: close fp_drvdb */
    fclose (fp_drvdb);

#endif

/* Finally, we need to sort the list into presentation order, based on the
   sequence number in the dispatch ttable entries. */

    qsort( dispatch_table, npldrivers, sizeof(PLDispatchTable*),
           plDispatchSequencer );
}

/*--------------------------------------------------------------------------*\
 * void plSelectDev()
 *
 * If the user has not already specified the output device, or the
 * one specified is either: (a) not available, (b) "?", or (c) NULL, the
 * user is prompted for it.
 *
 * Prompting quits after 10 unsuccessful tries in case the user has
 * run the program in the background with insufficient input.
\*--------------------------------------------------------------------------*/

static void
plSelectDev(void)			/* pmr: prototype */
{
    int dev, i, count, length;
    char response[80];
    int tlen;
    
/* Device name already specified.  See if it is valid. */

    if (*(plsc->DevName) != '\0' && *(plsc->DevName) != '?') {
	length = strlen(plsc->DevName);
	for (i = 0; i < npldrivers; i++) {
	    if ((*plsc->DevName == *dispatch_table[i]->pl_DevName) &&
		(strncmp(plsc->DevName,
			 dispatch_table[i]->pl_DevName, length) == 0))
		break;
	}
	if (i < npldrivers) {
	    plsc->device = i + 1;
	    return;
	}
	else {
	    fprintf(stderr, "Requested device %s not available\n",
		    plsc->DevName);
	}
    }

    dev = 0;
    count = 0;

    if (npldrivers == 1)
	dev = 1;

/* User hasn't specified it correctly yet, so we prompt */

    while (dev < 1 || dev > npldrivers) {
	fprintf(stdout, "\nPlotting Options:\n");
	for (i = 0; i < npldrivers; i++) {
	    fprintf(stdout, " <%2d> %-10s %s\n", i + 1,
		    dispatch_table[i]->pl_DevName,
		    dispatch_table[i]->pl_MenuStr);
	}
	if (ipls == 0)
	    fprintf(stdout, "\nEnter device number or keyword: ");
	else
	    fprintf(stdout, "\nEnter device number or keyword (stream %d): ",
		   (int) ipls);

	plio_fgets(response, sizeof(response), stdin);

    /* First check to see if device keyword was entered. */
    /* Final "\n" in response messes things up, so ignore it.  */

	length = strlen(response);
	if(!length)
	{
	    fprintf(stderr,"Error: empty response\n");
	    exit(-1);
	}
	
	tlen = length - 1;
	if (*(response + tlen) == '\n')
	    length--;

	for (i = 0; i < npldrivers; i++) {
	    if ( ! strncmp(response, dispatch_table[i]->pl_DevName,
			   (unsigned int) length))
		break;
	}
	if (i < npldrivers) {
	    dev = i + 1;
	}
	else {
	    if ((dev = atoi(response)) < 1) {
		fprintf(stdout, "\nInvalid device: %s", response);
		dev = 0;
	    }
	}
	if (count++ > 10)
	    plexit("plSelectDev: Too many tries.");
    }
    plsc->device = dev;
    strcpy(plsc->DevName, dispatch_table[dev - 1]->pl_DevName);
}

/*--------------------------------------------------------------------------*\
 * void plLoadDriver()
 *
 * Make sure the selected driver is loaded.  Static drivers are already
 * loaded, but if the user selected a dynamically loadable driver, we may
 * have to take care of that now.
\*--------------------------------------------------------------------------*/

static void
plLoadDriver(void)
{
#ifdef ENABLE_DYNDRIVERS
    int i, drvidx;
    char sym[60];
    char *tag;

    int n=plsc->device - 1;
    PLDispatchTable *dev = dispatch_table[n];
    PLLoadableDriver *driver = 0;

/* If the dispatch table is already filled in, then either the device was
 * linked in statically, or else perhaps it was already loaded.  In either
 * case, we have nothing left to do. */
    if (dev->pl_init)
        return;

    pldebug("plLoadDriver", "Device not loaded!\n");

/* Now search through the list of loadable devices, looking for the record
 * that corresponds to the requested device. */
    for( i=0; i < npldynamicdevices; i++ )
        if (strcmp( dev->pl_DevName, loadable_device_list[i].devnam ) == 0)
            break;

/* If we couldn't find such a record, then there is some sort of internal
 * logic flaw since plSelectDev is supposed to only select a valid device.
 */
    if (i == npldynamicdevices) {
        fprintf( stderr, "No such device: %s.\n", dev->pl_DevName );
        plexit("plLoadDriver detected device logic screwup");
    }

/* Note the device tag, and the driver index. Note that a given driver could
 * supply multiple devices, each with a unique tag to distinguish the driver
 * entry points for the differnet supported devices. */
    tag = loadable_device_list[i].tag;
    drvidx = loadable_device_list[i].drvidx;

    pldebug("plLoadDriver", "tag=%s, drvidx=%d\n", tag, drvidx );

    driver = &loadable_driver_list[drvidx];

/* Load the driver if it hasn't been loaded yet. */
    if (!driver->dlhand)
    {
        char drvspec[ 400 ];
        sprintf( drvspec, "%s/%s", plGetDrvDir (), driver->drvnam );

	pldebug("plLoadDriver", "Trying to load %s on %s\n",
		driver->drvnam, drvspec );

        driver->dlhand = lt_dlopenext( drvspec);
    }

/* If it still isn't loaded, then we're doomed. */
    if (!driver->dlhand)
    {
        pldebug("plLoadDriver", "lt_dlopenext failed because of "
		 "the following reason:\n%s\n", lt_dlerror ());
        fprintf( stderr, "Unable to load driver: %s.\n", driver->drvnam );
        plexit("Unable to load driver");
    }

/* Now we are ready to ask the driver's device dispatch init function to
   initialize the entries in the dispatch table. */

    sprintf( sym, "plD_dispatch_init_%s", tag );
    {
        PLDispatchInit dispatch_init = (PLDispatchInit) lt_dlsym( driver->dlhand, sym );
        if (!dispatch_init)
        {
            fprintf( stderr,
                     "Unable to locate dispatch table initialization function for driver: %s.\n",
		     driver->drvnam );
            return;
        }

        (*dispatch_init)( dev );
    }
#endif
}

/*--------------------------------------------------------------------------*\
 * void plfontld()
 *
 * Load specified font set.
\*--------------------------------------------------------------------------*/

void
c_plfontld(PLINT ifont)
{
    if (ifont != 0)
	ifont = 1;

    if (plsc->level > 0)
	plfntld(ifont);
    else
	initfont = ifont;
}

/*--------------------------------------------------------------------------*\
 * void plreplot()
 *
 * Replays contents of plot buffer to current device/file.
\*--------------------------------------------------------------------------*/

void
c_plreplot(void)
{
#ifdef BUFFERED_FILE
    if (plsc->plbufFile != NULL) {
#else
    if (plsc->plbuf_buffer != NULL) {
#endif
	plRemakePlot(plsc);
    }
    else {
	plwarn("plreplot: plot buffer not available");
    }
}

/*--------------------------------------------------------------------------*\
 * void plgFileDevs()
 *
 * Returns a list of file-oriented device names and their menu strings,
 * for use in a graphical interface.  The caller must allocate enough
 * space for (*p_menustr) and (*p_devname) to hold a pointer for each
 * device -- 20 or so is plenty.  E.g. char *menustr[20].  The size of
 * these arrays should be passed in *p_ndev, which, on exit, holds the
 * number of devices actually present.
\*--------------------------------------------------------------------------*/

void					/* pmr: const  */
plgFileDevs(const char ***p_menustr, const char ***p_devname, int *p_ndev)
{
    plgdevlst(*p_menustr, *p_devname, p_ndev, 0);
}

/*--------------------------------------------------------------------------*\
 * void plgDevs()
 *
 * Like plgFileDevs(), but returns names and menu strings for all devices.
\*--------------------------------------------------------------------------*/

void					/* pmr: const  */
plgDevs(const char ***p_menustr, const char ***p_devname, int *p_ndev)
{
    plgdevlst(*p_menustr, *p_devname, p_ndev, -1);
}

static void				/* pmr: const */
plgdevlst(const char **p_menustr, const char **p_devname, int *p_ndev, int type)
{
    int i, j;

    pllib_init();

    for (i = j = 0; i < npldrivers; i++) {
	if (type < 0 || dispatch_table[i]->pl_type == type) {
	    p_menustr[j] = dispatch_table[i]->pl_MenuStr;
	    p_devname[j] = dispatch_table[i]->pl_DevName;
	    if (++j + 1 >= *p_ndev) {
	        plwarn("plgdevlst:  too many devices");
		break;
	      }
	}
    }
    p_menustr[j] = NULL;
    p_devname[j] = NULL;
    *p_ndev = j;
}

/*--------------------------------------------------------------------------*\
 *  Various external access routines.
\*--------------------------------------------------------------------------*/

/* Get output device parameters. */

void
c_plgpage(PLFLT *p_xp, PLFLT *p_yp,
	  PLINT *p_xleng, PLINT *p_yleng, PLINT *p_xoff, PLINT *p_yoff)
{
    *p_xp = plsc->xdpi;
    *p_yp = plsc->ydpi;
    *p_xleng = plsc->xlength;
    *p_yleng = plsc->ylength;
    *p_xoff = plsc->xoffset;
    *p_yoff = plsc->yoffset;
}

/* Set output device parameters.  Usually ignored by the driver. */

void
c_plspage(PLFLT xp, PLFLT yp, PLINT xleng, PLINT yleng, PLINT xoff, PLINT yoff)
{
    if (plsc->level > 0)
        plwarn("calling plspage() after plinit() may give unpredictable results");

    if (xp)
	plsc->xdpi = xp;
    if (yp)
	plsc->ydpi = yp;

    if (xleng)
	plsc->xlength = xleng;
    if (yleng)
	plsc->ylength = yleng;

    if (xoff)
	plsc->xoffset = xoff;
    if (yoff)
	plsc->yoffset = yoff;

    plsc->pageset = 1;
}

/* Set the number of subwindows in x and y */

void
c_plssub(PLINT nx, PLINT ny)
{
    if (nx > 0)
	plsc->nsubx = nx;
    if (ny > 0)
	plsc->nsuby = ny;

/* Force a page advance */

    if (plsc->level > 0) {
        plP_subpInit();
/*AWI	plP_eop();
	plP_bop();*/
    }
}

/* Set the device (keyword) name */

void
c_plsdev(const char *devname)
{
    if (plsc->level > 0) {
	plwarn("plsdev: Must be called before plinit.");
	return;
    }
    if (devname != NULL) {
	strncpy(plsc->DevName, devname, sizeof(plsc->DevName) - 1);
	plsc->DevName[sizeof(plsc->DevName) - 1] = '\0';
    }
}

/* Get the current device (keyword) name */
/* Note: you MUST have allocated space for this (80 characters is safe) */

void
c_plgdev(char *p_dev)
{
    strcpy(p_dev, plsc->DevName);
}

/* Set the memory area to be plotted (with the 'mem' driver) as the 'dev'
   member of the stream structure.  Also set the number
   of pixels in the memory passed in in 'plotmem'.
   Plotmem is a block of memory maxy by maxx by 3 bytes long, say:
   480 x 640 x 3 (Y, X, RGB)

   This memory will be freed by the user!
*/

void
c_plsmem(PLINT maxx, PLINT maxy, void *plotmem)
{
    plsc->dev = plotmem;
    plP_setphy (0, maxx, 0, maxy);
}

/* Get the current stream pointer */

void
plgpls(PLStream **p_pls)
{
    *p_pls = plsc;
}

/* Get the (current) run level.
 * Valid settings are:
 *   0	uninitialized
 *   1	initialized
 *   2	viewport defined
 *   3	world coords defined
 */

void
c_plglevel(PLINT *p_level)
{
    *p_level = plsc->level;
}

/* Set the function pointer for the keyboard event handler */

void
plsKeyEH(void (*KeyEH) (PLGraphicsIn *, void *, int *),
	 void *KeyEH_data)
{
    plsc->KeyEH = KeyEH;
    plsc->KeyEH_data = KeyEH_data;
}

/* Set the function pointer for the (mouse) button event handler */

void
plsButtonEH(void (*ButtonEH) (PLGraphicsIn *, void *, int *),
	    void *ButtonEH_data)
{
    plsc->ButtonEH = ButtonEH;
    plsc->ButtonEH_data = ButtonEH_data;
}

/* Sets an optional user bop handler. */

void
plsbopH(void (*handler) (void *, int *), void *handler_data)
{
    plsc->bop_handler = handler;
    plsc->bop_data = handler_data;
}

/* Sets an optional user eop handler. */

void
plseopH(void (*handler) (void *, int *), void *handler_data)
{
    plsc->eop_handler = handler;
    plsc->eop_data = handler_data;
}

/* Set the variables to be used for storing error info */

void
plsError(PLINT *errcode, char *errmsg)
{
    if (errcode != NULL)
	plsc->errcode = errcode;

    if (errmsg != NULL)
	plsc->errmsg = errmsg;
}

/* Set orientation.  Must be done before calling plinit. */

void
c_plsori(PLINT ori)
{
    plsdiori((PLFLT) ori);
}

/*
 * Set pen width.  Can be done any time, but before calling plinit is best
 * since otherwise it may be volatile (i.e. reset on next page advance).
 * If width < 0 or is unchanged by the call, nothing is done.
 */

void
c_plwid(PLINT width)
{
    if (width != plsc->width && width >= 0) {
	plsc->width = width;

	if (plsc->level > 0) {
	    if ( ! plsc->widthlock)
		plP_state(PLSTATE_WIDTH);
	}
    }
}

/* Set the output file pointer */

void
plgfile(FILE **p_file)
{
    *p_file = plsc->OutFile;
}

/* Get the output file pointer */

void
plsfile(FILE *file)
{
    plsc->OutFile = file;
}

/* Get the (current) output file name.  Must be preallocated to >=80 bytes */
/* Beyond that, I truncate it.  You have been warned. */

void
c_plgfnam(char *fnam)
{
    if (fnam == NULL) {
	plabort("filename string must be preallocated to >=80 bytes");
	return;
    }

    *fnam = '\0';
    if (plsc->FileName != NULL) {
	strncpy(fnam, plsc->FileName, 79);
	fnam[79] = '\0';
    }
}

/* Set the output file name. */

void
c_plsfnam(const char *fnam)
{
    plP_sfnam(plsc, fnam);
}

void
c_plxsfnam(const char *fnam, const char* ext)
{
    plPX_sfnam(plsc, fnam, ext);
}

/* Set the pause (on end-of-page) status */

void
c_plspause(PLINT mypause)		/* pmr: pause in unistd.h */
{
    plsc->nopause = ! mypause;
}

/* Set the floating point precision (in number of places) in numeric labels. */

void
c_plprec(PLINT setp, PLINT prec)
{
    plsc->setpre = setp;
    plsc->precis = prec;
}

/* Get the floating point precision (in number of places) in numeric labels. */

void
plP_gprec(PLINT *p_setp, PLINT *p_prec)
{
    *p_setp = plsc->setpre;
    *p_prec = plsc->precis;
}

/*
 * Set the escape character for text strings.
 * From C you can pass as a character, from Fortran it needs to be the decimal
 * ASCII value.  Only selected characters are allowed to prevent the user from
 * shooting himself in the foot (a '\' isn't allowed since it conflicts with
 * C's use of backslash as a character escape).
 */

void
c_plsesc(char esc)
{
    switch (esc) {
	case '!':		/* ASCII 33 */
	case '#':		/* ASCII 35 */
	case '$':		/* ASCII 36 */
	case '%':		/* ASCII 37 */
	case '&':		/* ASCII 38 */
	case '*':		/* ASCII 42 */
	case '@':		/* ASCII 64 */
	case '^':		/* ASCII 94 */
	case '~':		/* ASCII 126 */
	plsc->esc = esc;
	break;

      default:
	plwarn("plsesc: Invalid escape character, ignoring.");
    }
}

/* Get the escape character for text strings. */

void
plgesc(unsigned char *p_esc)
{
    if (plsc->esc == '\0')
	plsc->esc = '#';

    *p_esc = plsc->esc;
}

/* Set the FCI (font characterization integer) for unicode-enabled device
 * drivers.
 */
void
c_plsfci(PLUNICODE fci)
{
   /* Always mark FCI as such. */
   plsc->fci = fci | PL_FCI_MARK;
}

/* Get the FCI (font characterization integer) for unicode-enabled device
 * drivers.
 */
void
c_plgfci(PLUNICODE *pfci)
{
   /* Always mark FCI as such. */
   *pfci = plsc->fci | PL_FCI_MARK;
}
/* Store hex digit value shifted to the left by hexdigit hexadecimal digits
 * into pre-existing FCI.
 */
void
plP_hex2fci(unsigned char hexdigit, unsigned char hexpower, PLUNICODE *pfci)
{
   PLUNICODE mask;
   hexpower = hexpower & PL_FCI_HEXPOWER_MASK;
   mask = ~ (((PLUNICODE) PL_FCI_HEXDIGIT_MASK) << ((PLUNICODE) 4*hexpower));
   *pfci = *pfci & mask;
   mask = (((PLUNICODE) (hexdigit & PL_FCI_HEXDIGIT_MASK)) << (4*hexpower));
   *pfci = *pfci | mask;
}

/* Retrieve hex digit value from FCI that is masked out and shifted to the
 * right by hexpower hexadecimal digits. */
void
plP_fci2hex(PLUNICODE fci, unsigned char *phexdigit, unsigned char hexpower)
{
   PLUNICODE mask;
   hexpower = hexpower & PL_FCI_HEXPOWER_MASK;
   mask = (((PLUNICODE) PL_FCI_HEXPOWER_MASK) << ((PLUNICODE) (4*hexpower)));
   *phexdigit = (unsigned char) ((fci & mask) >>
				 ((PLUNICODE) (4*hexpower)));
}

/* Get the current library version number */
/* Note: you MUST have allocated space for this (80 characters is safe) */
void
c_plgver(char *p_ver)
{
    strcpy(p_ver, PLPLT_VERSION);
}

/* Set inferior X window */

void
plsxwin(PLINT window_id)
{
    plsc->window_id = window_id;
}

/*--------------------------------------------------------------------------*\
 *  These set/get information for family files, and may be called prior
 *  to plinit to set up the necessary parameters.  Arguments:
 *
 *	fam	familying flag (boolean)
 *	num	member number
 *	bmax	maximum member size
\*--------------------------------------------------------------------------*/

/* Get family file parameters */

void
c_plgfam(PLINT *p_fam, PLINT *p_num, PLINT *p_bmax)
{
    *p_fam = plsc->family;
    *p_num = plsc->member;
    *p_bmax = plsc->bytemax;
}

/* Set family file parameters */

void
c_plsfam(PLINT fam, PLINT num, PLINT bmax)
{
    if (plsc->level > 0)
	plwarn("plsfam: Must be called before plinit.");

    if (fam >= 0)
	plsc->family = fam;
    if (num >= 0)
	plsc->member = num;
    if (bmax >= 0)
	plsc->bytemax = bmax;
}

/* Advance to the next family file on the next new page */

void
c_plfamadv(void)
{
    plsc->famadv = 1;
}

/*--------------------------------------------------------------------------*\
 *  Interface routines for axis labling parameters.
 *  See pldtik.c for more info.
\*--------------------------------------------------------------------------*/

/* Get x axis labeling parameters */

void
c_plgxax(PLINT *p_digmax, PLINT *p_digits)
{
    *p_digmax = plsc->xdigmax;
    *p_digits = plsc->xdigits;
}

/* Set x axis labeling parameters */

void
c_plsxax(PLINT digmax, PLINT digits)
{
    plsc->xdigmax = digmax;
    plsc->xdigits = digits;
}

/* Get y axis labeling parameters */

void
c_plgyax(PLINT *p_digmax, PLINT *p_digits)
{
    *p_digmax = plsc->ydigmax;
    *p_digits = plsc->ydigits;
}

/* Set y axis labeling parameters */

void
c_plsyax(PLINT digmax, PLINT digits)
{
    plsc->ydigmax = digmax;
    plsc->ydigits = digits;
}

/* Get z axis labeling parameters */

void
c_plgzax(PLINT *p_digmax, PLINT *p_digits)
{
    *p_digmax = plsc->zdigmax;
    *p_digits = plsc->zdigits;
}

/* Set z axis labeling parameters */

void
c_plszax(PLINT digmax, PLINT digits)
{
    plsc->zdigmax = digmax;
    plsc->zdigits = digits;
}

/* Get character default height and current (scaled) height */

void
c_plgchr(PLFLT *p_def, PLFLT *p_ht)
{
    *p_def = plsc->chrdef;
    *p_ht = plsc->chrht;
}

/* Get viewport boundaries in normalized device coordinates */

void
c_plgvpd(PLFLT *p_xmin, PLFLT *p_xmax, PLFLT *p_ymin, PLFLT *p_ymax)
{
    *p_xmin = plsc->vpdxmi;
    *p_xmax = plsc->vpdxma;
    *p_ymin = plsc->vpdymi;
    *p_ymax = plsc->vpdyma;
}

/* Get viewport boundaries in world coordinates */

void
c_plgvpw(PLFLT *p_xmin, PLFLT *p_xmax, PLFLT *p_ymin, PLFLT *p_ymax)
{
    *p_xmin = plsc->vpwxmi;
    *p_xmax = plsc->vpwxma;
    *p_ymin = plsc->vpwymi;
    *p_ymax = plsc->vpwyma;
}

/*--------------------------------------------------------------------------*\
 *  These should not be called by the user.
\*--------------------------------------------------------------------------*/

/* Get x-y domain in world coordinates for 3d plots */

void
plP_gdom(PLFLT *p_xmin, PLFLT *p_xmax, PLFLT *p_ymin, PLFLT *p_ymax)
{
    *p_xmin = plsc->domxmi;
    *p_xmax = plsc->domxma;
    *p_ymin = plsc->domymi;
    *p_ymax = plsc->domyma;
}

/* Get vertical (z) scale parameters for 3-d plot */

void
plP_grange(PLFLT *p_zscl, PLFLT *p_zmin, PLFLT *p_zmax)
{
    *p_zscl = plsc->zzscl;
    *p_zmin = plsc->ranmi;
    *p_zmax = plsc->ranma;
}

/* Get parameters used in 3d plots */

void
plP_gw3wc(PLFLT *p_dxx, PLFLT *p_dxy, PLFLT *p_dyx, PLFLT *p_dyy, PLFLT *p_dyz)
{
    *p_dxx = plsc->cxx;
    *p_dxy = plsc->cxy;
    *p_dyx = plsc->cyx;
    *p_dyy = plsc->cyy;
    *p_dyz = plsc->cyz;
}

/* Get clip boundaries in physical coordinates */

void
plP_gclp(PLINT *p_ixmin, PLINT *p_ixmax, PLINT *p_iymin, PLINT *p_iymax)
{
    *p_ixmin = plsc->clpxmi;
    *p_ixmax = plsc->clpxma;
    *p_iymin = plsc->clpymi;
    *p_iymax = plsc->clpyma;
}

/* Set clip boundaries in physical coordinates */

void
plP_sclp(PLINT ixmin, PLINT ixmax, PLINT iymin, PLINT iymax)
{
    plsc->clpxmi = ixmin;
    plsc->clpxma = ixmax;
    plsc->clpymi = iymin;
    plsc->clpyma = iymax;
}

/* Get physical device limits in physical coordinates */

void
plP_gphy(PLINT *p_ixmin, PLINT *p_ixmax, PLINT *p_iymin, PLINT *p_iymax)
{
    *p_ixmin = plsc->phyxmi;
    *p_ixmax = plsc->phyxma;
    *p_iymin = plsc->phyymi;
    *p_iymax = plsc->phyyma;
}

/* Get number of subpages on physical device and current subpage */

void
plP_gsub(PLINT *p_nx, PLINT *p_ny, PLINT *p_cs)
{
    *p_nx = plsc->nsubx;
    *p_ny = plsc->nsuby;
    *p_cs = plsc->cursub;
}

/* Set number of subpages on physical device and current subpage */

void
plP_ssub(PLINT nx, PLINT ny, PLINT cs)
{
    plsc->nsubx = nx;
    plsc->nsuby = ny;
    plsc->cursub = cs;
}

/* Get number of pixels to a millimeter */

void
plP_gpixmm(PLFLT *p_x, PLFLT *p_y)
{
    *p_x = plsc->xpmm;
    *p_y = plsc->ypmm;
}

/* All the drivers call this to set physical pixels/mm. */

void
plP_setpxl(PLFLT xpmm, PLFLT ypmm)
{
    plsc->xpmm = xpmm;
    plsc->ypmm = ypmm;
    plsc->umx = 1000.0 / plsc->xpmm;
    plsc->umy = 1000.0 / plsc->ypmm;
}

/* Sets up physical limits of plotting device. */

void
plP_setphy(PLINT xmin, PLINT xmax, PLINT ymin, PLINT ymax)
{
    if (xmin > xmax || ymin > ymax)
	plexit("plP_setphy: device minima must not exceed maxima");

    plsc->phyxmi = xmin;
    plsc->phyxma = xmax;
    plsc->phyymi = ymin;
    plsc->phyyma = ymax;
    plsc->phyxlen = xmax - xmin;
    plsc->phyylen = ymax - ymin;
}

/*--------------------------------------------------------------------------*\
 * void c_plscompression()
 *
 * Set compression.
 * Has to be done before plinit.
\*--------------------------------------------------------------------------*/

void
c_plscompression(PLINT compression)
{
  if (plsc->level <= 0)
     {
      plsc->dev_compression=compression;
     }
}

/*--------------------------------------------------------------------------*\
 * void c_plgcompression()
 *
 * Get compression
\*--------------------------------------------------------------------------*/

void
c_plgcompression(PLINT *compression)
{
    *compression = plsc->dev_compression;
}


/*--------------------------------------------------------------------------*\
 * void plP_getinitdriverlist()
 *
 * Check to see if a driver/stream has been initialised
 * Returns a space separated list of matches streams/drivers
 * If more than one stream uses the same device, then the device name
 * will be returned for each stream.
 * Caller must allocate enough memory for "names" to hold the answer.
\*--------------------------------------------------------------------------*/

void
plP_getinitdriverlist(char *names)
{
int i;

for (i=0;i<PL_NSTREAMS;++i)
   {
    if (pls[i]!=NULL)
       {
       if (i==0)
          strcpy(names,pls[i]->DevName);
       else
          {
          strcat(names," ");
          strcat(names,pls[i]->DevName);
          }
       }
    else
       break;
   }
}


/*--------------------------------------------------------------------------*\
 * PLINT plP_checkdriverinit()
 *
 * Checks from a list of given drivers which ones have been initialised
 * and returns the number of devices matching the list, or -1 if in error.
 * Effectively returns the number of streams matching the given stream.
\*--------------------------------------------------------------------------*/

PLINT plP_checkdriverinit( char *names)
{
char *buff;
char *tok=NULL;
PLINT ret=0;   /* set up return code to 0, the value if no devices match*/

buff=(char *)malloc((size_t) PL_NSTREAMS*8); /* Allocate enough memory for 8
                                                characters for each possible stream */

if (buff!=NULL)
   {
    memset(buff,0,PL_NSTREAMS*8);    /* Make sure we clear it               */
    plP_getinitdriverlist(buff);     /* Get the list of initialised devices */

    for (tok = strtok(buff, " ,");   /* Check each device against the "name" */
         tok; tok=strtok(0, " ,"))   /* supplied to the subroutine   */
        {
        if (strstr(names,tok)!=NULL)  /* Check to see if the device has been initialised */
           {
            ret++;                   /* Bump the return code if it has      */
           }
        }
    free(buff);                      /* Clear up that memory we allocated   */
    }
else
   ret=-1;                           /* Error flag */

return(ret);
}


/*--------------------------------------------------------------------------*\
 * plP_image
 *
 * Author: Alessandro Mirone, Nov 2001
 *
 *
 *
\*--------------------------------------------------------------------------*/

void
plP_image(short *x, short *y, unsigned short *z , PLINT nx, PLINT ny, PLFLT xmin, PLFLT ymin, PLFLT dx, PLFLT dy, unsigned short zmin, unsigned short zmax)
{
  PLINT i, npts;
  short *myxscl, *myyscl;
  int   plbuf_write;

  plsc->page_status = DRAWING;

  if (plsc->dev_fastimg == 0) {
    plimageslow(x, y, z, nx-1, ny-1,
         xmin, ymin, dx, dy, zmin, zmax);
    return ;
  }

  if (plsc->plbuf_write) {
    IMG_DT img_dt;

    img_dt.xmin=xmin;
    img_dt.ymin=ymin;
    img_dt.dx=dx;
    img_dt.dy=dy;

    plsc->dev_ix = x;
    plsc->dev_iy = y;
    plsc->dev_z = z;
    plsc->dev_nptsX = nx;
    plsc->dev_nptsY = ny;
    plsc->dev_zmin = zmin;
    plsc->dev_zmax = zmax;

    plbuf_esc(plsc, PLESC_IMAGE, &img_dt);
  }

  /* avoid re-saving plot buffer while in plP_esc() */
  plbuf_write = plsc->plbuf_write;
  plsc->plbuf_write = 0;

  npts = nx*ny;
  if (plsc->difilt) { /* isn't this odd? when replaying the plot buffer, e.g., when resizing the window, difilt() is caled again! the plot buffer should already contain the transformed data--it would save a lot of time! (and allow for differently oriented plots when in multiplot mode) */
    PLINT clpxmi, clpxma, clpymi, clpyma;

    myxscl = (short *) malloc(nx*ny*sizeof(short));
    myyscl = (short *) malloc(nx*ny*sizeof(short));
    for (i = 0; i < npts; i++) {
      myxscl[i] = x[i];
      myyscl[i] = y[i];
    }
    sdifilt(myxscl, myyscl, npts, &clpxmi, &clpxma, &clpymi, &clpyma);
    plsc->imclxmin = clpxmi;
    plsc->imclymin = clpymi;
    plsc->imclxmax = clpxma;
    plsc->imclymax = clpyma;
    grimage(myxscl, myyscl, z, nx, ny);
    free(myxscl);
    free(myyscl);
  } else {
    plsc->imclxmin = plsc->phyxmi;
    plsc->imclymin = plsc->phyymi;
    plsc->imclxmax = plsc->phyxma;
    plsc->imclymax = plsc->phyyma;
    grimage(x, y, z, nx, ny );
  }
  plsc->plbuf_write = plbuf_write;
}