File: term.c

package info (click to toggle)
gnuplot 4.0.0-2
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 9,448 kB
  • ctags: 6,623
  • sloc: ansic: 63,562; lisp: 5,011; cpp: 970; sh: 900; makefile: 753; objc: 647; asm: 539; csh: 297; awk: 235; pascal: 192; perl: 44
file content (2350 lines) | stat: -rw-r--r-- 64,949 bytes parent folder | download
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
#ifndef lint
static char *RCSid() { return RCSid("$Id: term.c,v 1.73 2004/04/13 17:24:02 broeker Exp $"); }
#endif

/* GNUPLOT - term.c */

/*[
 * Copyright 1986 - 1993, 1998, 2004   Thomas Williams, Colin Kelley
 *
 * Permission to use, copy, and distribute this software and its
 * documentation for any purpose with or without fee is hereby granted,
 * provided that the above copyright notice appear in all copies and
 * that both that copyright notice and this permission notice appear
 * in supporting documentation.
 *
 * Permission to modify the software is granted, but not the right to
 * distribute the complete modified source code.  Modifications are to
 * be distributed as patches to the released version.  Permission to
 * distribute binaries produced by compiling modified sources is granted,
 * provided you
 *   1. distribute the corresponding source modifications from the
 *    released version in the form of a patch file along with the binaries,
 *   2. add special version identification to distinguish your version
 *    in addition to the base release version number,
 *   3. provide your name and address as the primary contact for the
 *    support of your modified version, and
 *   4. retain our contact information in regard to use of the base
 *    software.
 * Permission to distribute the released version of the source code along
 * with corresponding source modifications in the form of a patch file is
 * granted with same provisions 2 through 4 for binary distributions.
 *
 * This software is provided "as is" without express or implied warranty
 * to the extent permitted by applicable law.
]*/


 /* This module is responsible for looking after the terminal
  * drivers at the lowest level. Only this module (should)
  * know about all the various rules about interpreting
  * the terminal capabilities exported by the terminal
  * drivers in the table.
  *
  * Note that, as far as this module is concerned, a
  * terminal session lasts only until _either_ terminal
  * or output file changes. Before either is changed,
  * the terminal is shut down.
  * 
  * Entry points : (see also term/README)
  *
  * term_set_output() : called when  set output  invoked
  *
  * term_init()  : optional. Prepare the terminal for first
  *                use. It protects itself against subsequent calls.
  *
  * term_start_plot() : called at start of graph output. Calls term_init
  *                     if necessary
  *
  * term_apply_lp_properties() : apply linewidth settings
  *
  * term_end_plot() : called at the end of a plot
  *
  * term_reset() : called during int_error handling, to shut
  *                terminal down cleanly
  *
  * term_start_multiplot() : called by   set multiplot
  *
  * term_end_multiplot() : called by  set nomultiplot
  *
  * term_check_multiplot_okay() : called just before an interactive
  *                        prompt is issued while in multiplot mode,
  *                        to allow terminal to suspend if necessary,
  *                        Raises an error if interactive multiplot
  *                       is not supported.
  */

#include "term_api.h"

#include "alloc.h"
#include "axis.h"
#include "bitmap.h"
#include "command.h"
#include "driver.h"
#include "graphics.h"
#include "help.h"
#include "plot.h"
#include "tables.h"
#include "term.h"
#include "util.h"
#include "version.h"
#include "misc.h"

#ifdef USE_MOUSE
#include "mouse.h"
static int save_mouse_state = 1;
#endif

#ifdef _Windows
FILE *open_printer __PROTO((void));	/* in wprinter.c */
void close_printer __PROTO((FILE * outfile));
# ifdef __MSC__
#  include <malloc.h>
# else
#  include <alloc.h>
# endif				/* MSC */
#endif /* _Windows */

enum { UNSET = -1, no = 0, yes = 1 }; /* FIXME HBB 20001031: should this be here? */

static int termcomp __PROTO((const generic * a, const generic * b));

/* Externally visible variables */
/* the central instance: the current terminal's interface structure */
struct termentry *term = NULL;	/* unknown */

/* ... and its options string */
char term_options[MAX_LINE_LEN+1] = "";

/* the 'output' file name and handle */
char *outstr = NULL;		/* means "STDOUT" */
FILE *gpoutfile;

#ifdef PM3D
/* Output file where the PostScript output goes to. See term_api.h for more
   details.
*/
FILE *postscript_gpoutfile = 0;
#endif

/* true if terminal has been initialized */
TBOOLEAN term_initialised;

/* true if in multiplot mode */
TBOOLEAN multiplot = FALSE;

/* flag variable to disable enhanced output of filenames, mainly */
TBOOLEAN ignore_enhanced_text = FALSE;

/* text output encoding, for terminals that support it */
enum set_encoding_id encoding;
/* table of encoding names, for output of the setting */
const char *encoding_names[] = {
    "default", "iso_8859_1", "iso_8859_2", "iso_8859_15",
    "cp437", "cp850", "cp852", "koi8r", NULL };
/* 'set encoding' options */
const struct gen_table set_encoding_tbl[] =
{
    { "def$ault", S_ENC_DEFAULT },
    { "iso$_8859_1", S_ENC_ISO8859_1 },
    { "iso_8859_2", S_ENC_ISO8859_2 },
    { "iso_8859_15", S_ENC_ISO8859_15 },
    { "cp4$37", S_ENC_CP437 },
    { "cp8$50", S_ENC_CP850 },
    { "cp8$52", S_ENC_CP852 },
    { "koi8$r", S_ENC_KOI8_R },
    { NULL, S_ENC_INVALID }
};

const char *arrow_head_names[3] = {"nohead", "head", "heads"};

/* HBB 20020225: moved here, from ipc.h, where it never should have
 * been. */
#ifdef PIPE_IPC
/* HBB 20020225: currently not used anywhere outside term.c --> make
 * it static */
static SELECT_TYPE_ARG1 ipc_back_fd = IPC_BACK_CLOSED;
int isatty_state = 1;
#endif

/* Internal variables */

/* true if terminal is in graphics mode */
static TBOOLEAN term_graphics = FALSE;

/* we have suspended the driver, in multiplot mode */
static TBOOLEAN term_suspended = FALSE;

/* true if? */
static TBOOLEAN opened_binary = FALSE;

/* true if require terminal to be initialized */
static TBOOLEAN term_force_init = FALSE;

/* internal pointsize for do_point */
static double term_pointsize=1;

/* Internal prototypes: */

static void term_suspend __PROTO((void));
static void term_close_output __PROTO((void));
static void null_linewidth __PROTO((double));

static void do_point __PROTO((unsigned int x, unsigned int y, int number));
static void do_pointsize __PROTO((double size));
static void line_and_point __PROTO((unsigned int x, unsigned int y, int number));
static void do_arrow __PROTO((unsigned int sx, unsigned int sy, unsigned int ex, unsigned int ey, int head));

static void UP_redirect __PROTO((int called));

static int null_text_angle __PROTO((int ang));
static int null_justify_text __PROTO((enum JUSTIFY just));
static int null_scale __PROTO((double x, double y));
static void options_null __PROTO((void));
static void UNKNOWN_null __PROTO((void));
static void MOVE_null __PROTO((unsigned int, unsigned int));
static void LINETYPE_null __PROTO((int));
static void PUTTEXT_null __PROTO((unsigned int, unsigned int, const char *));
static int set_font_null __PROTO((const char *s));

/* Support for enhanced text mode. These can be static because all  */
/* the terminal drivers are included into term.c at compile time.   */
static char  enhanced_text[MAX_LINE_LEN];
static char *enhanced_cur_text;
static double enhanced_fontscale;
static char enhanced_escape_format[16];
static double enhanced_max_height, enhanced_min_height;
char * enhanced_recursion __PROTO((char *p, TBOOLEAN brace,
	     char *fontname, double fontsize, double base, 
	     TBOOLEAN widthflag, TBOOLEAN showflag, int overprint));
static void enh_err_check __PROTO((const char *str));
static void do_enh_writec __PROTO((char c));

#ifdef __ZTC__
char *ztc_init();
/* #undef TGIF */
#endif

#ifdef VMS
char *vms_init();
void vms_reset();
void term_mode_tek();
void term_mode_native();
void term_pasthru();
void term_nopasthru();
void fflush_binary();
# define FOPEN_BINARY(file) fopen(file, "wb", "rfm=fix", "bls=512", "mrs=512")
#else /* !VMS */
# define FOPEN_BINARY(file) fopen(file, "wb")
#endif /* !VMS */

#if defined(MSDOS) || defined(WIN32) || defined(WIN16)
# if defined(__DJGPP__) || defined (__TURBOC__)
#  include <io.h>
# endif
# include <fcntl.h>
# ifndef O_BINARY
#  ifdef _O_BINARY
#   define O_BINARY _O_BINARY
#  else
#   define O_BINARY O_BINARY_is_not_defined
#  endif
# endif
#endif

#ifdef __EMX__
#include <io.h>
#include <fcntl.h>
#endif

/* This is needed because the unixplot library only writes to stdout,
 * but GNU plotutils libplot.a doesn't */
#if defined(UNIXPLOT) && !defined(GNUGRAPH)
static FILE save_stdout;
#endif
static int unixplot = 0;

#if defined(MTOS) || defined(ATARI)
int aesid = -1;
#endif

#define NICE_LINE		0
#define POINT_TYPES		6

#ifndef DEFAULTTERM
# define DEFAULTTERM NULL
#endif

/* interface to the rest of gnuplot - the rules are getting
 * too complex for the rest of gnuplot to be allowed in
 */

#if defined(PIPES)
static TBOOLEAN output_pipe_open = FALSE;
#endif /* PIPES */

static void
term_close_output()
{
    FPRINTF((stderr, "term_close_output\n"));

    opened_binary = FALSE;

    if (!outstr)		/* ie using stdout */
	return;

#if defined(PIPES)
    if (output_pipe_open) {
	(void) pclose(gpoutfile);
	output_pipe_open = FALSE;
    } else
#endif /* PIPES */
#ifdef _Windows
    if (stricmp(outstr, "PRN") == 0)
	close_printer(gpoutfile);
    else
#endif
	(void) fclose(gpoutfile);

    gpoutfile = stdout;		/* Don't dup... */
    free(outstr);
    outstr = NULL;
}

#ifdef OS2
# define POPEN_MODE ("wb")
#else
# define POPEN_MODE ("w")
#endif

/* assigns dest to outstr, so it must be allocated or NULL
 * and it must not be outstr itself !
 */
void
term_set_output(dest)
char *dest;
{
    FILE *f = NULL;

    FPRINTF((stderr, "term_set_output\n"));
    assert(dest == NULL || dest != outstr);

    if (multiplot) {
	fputs("In multiplotmode you can't change the output\n", stderr);
	return;
    }
    if (term && term_initialised) {
	(*term->reset) ();
	term_initialised = FALSE;
#ifdef PM3D
	/* switch off output to special postscript file (if used) */
	postscript_gpoutfile = 0;
#endif
    }
    if (dest == NULL) {		/* stdout */
	UP_redirect(4);
	term_close_output();
    } else {

#if defined(PIPES)
	if (*dest == '|') {
	    if ((f = popen(dest + 1, POPEN_MODE)) == (FILE *) NULL)
		os_error(c_token, "cannot create pipe; output not changed");
	    else
		output_pipe_open = TRUE;
	} else {
#endif /* PIPES */

#ifdef _Windows
	if (outstr && stricmp(outstr, "PRN") == 0) {
	    /* we can't call open_printer() while printer is open, so */
	    close_printer(gpoutfile);	/* close printer immediately if open */
	    gpoutfile = stdout;	/* and reset output to stdout */
	    free(outstr);
	    outstr = NULL;
	}
	if (stricmp(dest, "PRN") == 0) {
	    if ((f = open_printer()) == (FILE *) NULL)
		os_error(c_token, "cannot open printer temporary file; output may have changed");
	} else
#endif

	{
#if defined (MSDOS)
	    if (outstr && (0 == stricmp(outstr, dest))) {
		/* On MSDOS, you cannot open the same file twice and
		 * then close the first-opened one and keep the second
		 * open, it seems. If you do, you get lost clusters
		 * (connection to the first version of the file is
		 * lost, it seems). */
		/* FIXME: this is not yet safe enough. You can fool it by
		 * specifying the same output file in two different ways
		 * (relative vs. absolute path to file, e.g.) */
		term_close_output();
	    }
#endif
            if (term && (term->flags & TERM_BINARY))
		f = FOPEN_BINARY(dest);
            else
		f = fopen(dest, "w");

	    if (f == (FILE *) NULL)
		os_error(c_token, "cannot open file; output not changed");
	}
#if defined(PIPES)
	}
#endif
	
	term_close_output();
	gpoutfile = f;
	outstr = dest;
	opened_binary = (term && (term->flags & TERM_BINARY));
	UP_redirect(1);
    }
}

void
term_init()
{
    FPRINTF((stderr, "term_init()\n"));

    if (!term)
	int_error(NO_CARET, "No terminal defined");

    /* check if we have opened the output file in the wrong mode
     * (text/binary), if set term comes after set output
     * This was originally done in change_term, but that
     * resulted in output files being truncated
     */

    if (outstr &&
	(((term->flags & TERM_BINARY) && !opened_binary) ||
	 ((!(term->flags & TERM_BINARY) && opened_binary)))) {
	/* this is nasty - we cannot just term_set_output(outstr)
	 * since term_set_output will first free outstr and we
	 * end up with an invalid pointer. I think I would
	 * prefer to defer opening output file until first plot.
	 */
	char *temp = gp_alloc(strlen(outstr) + 1, "temp file string");
	if (temp) {
	    FPRINTF((stderr, "term_init : reopening \"%s\" as %s\n",
		     outstr, term->flags & TERM_BINARY ? "binary" : "text"));
	    strcpy(temp, outstr);
	    term_set_output(temp);	/* will free outstr */
	} else
	    fputs("Cannot reopen output file in binary", stderr);
	/* and carry on, hoping for the best ! */
    }
#if defined(MSDOS) || defined (_Windows) || defined(OS2)
# ifdef _Windows
    else if (!outstr && (term->flags & TERM_BINARY))
# else
    else if (!outstr && !interactive && (term->flags & TERM_BINARY))
# endif
	{
	    /* binary to stdout in non-interactive session... */
	    fflush(stdout);
	    setmode(fileno(stdout), O_BINARY);
	}
#endif


    if (!term_initialised || term_force_init) {
	FPRINTF((stderr, "- calling term->init()\n"));
	(*term->init) ();
	term_initialised = TRUE;
    }
}


void
term_start_plot()
{
    FPRINTF((stderr, "term_start_plot()\n"));

    if (!term_initialised)
	term_init();

    if (!term_graphics) {
	FPRINTF((stderr, "- calling term->graphics()\n"));
	(*term->graphics) ();
	term_graphics = TRUE;
    } else if (multiplot && term_suspended) {
	if (term->resume) {
	    FPRINTF((stderr, "- calling term->resume()\n"));
	    (*term->resume) ();
	}
	term_suspended = FALSE;
    }
}

void
term_end_plot()
{
    FPRINTF((stderr, "term_end_plot()\n"));

    if (!term_initialised)
	return;

    if (!multiplot) {
	FPRINTF((stderr, "- calling term->text()\n"));
	(*term->text) ();
	term_graphics = FALSE;
    }
#ifdef VMS
    if (opened_binary)
	fflush_binary();
    else
#endif /* VMS */

	(void) fflush(gpoutfile);

#ifdef USE_MOUSE
    recalc_statusline();
    update_ruler();
#endif
}

void
term_start_multiplot()
{

    c_token++;
    FPRINTF((stderr, "term_start_multiplot()\n"));
    if (multiplot)
	term_end_multiplot();

    multiplot = TRUE;
    term_start_plot();

#ifdef USE_MOUSE
    /* save the state of mouse_setting.on and
     * disable mouse; call UpdateStatusline()
     * to turn of eventually statusline */
    save_mouse_state = mouse_setting.on;
    mouse_setting.on = 0;
    UpdateStatusline();
#endif
}

void
term_end_multiplot()
{
    FPRINTF((stderr, "term_end_multiplot()\n"));
    if (!multiplot)
	return;

    if (term_suspended) {
	if (term->resume)
	    (*term->resume) ();
	term_suspended = FALSE;
    }
    multiplot = FALSE;

    term_end_plot();
#ifdef USE_MOUSE
    /* restore the state of mouse_setting.on;
     * call UpdateStatusline() to turn on
     * eventually statusline */
    mouse_setting.on = save_mouse_state;
    UpdateStatusline();
#endif
}



static void
term_suspend()
{
    FPRINTF((stderr, "term_suspend()\n"));
    if (term_initialised && !term_suspended && term->suspend) {
	FPRINTF((stderr, "- calling term->suspend()\n"));
	(*term->suspend) ();
	term_suspended = TRUE;
    }
}

void
term_reset()
{
    FPRINTF((stderr, "term_reset()\n"));

#ifdef USE_MOUSE
    /* Make sure that ^C will break out of a wait for 'pause mouse' */
    paused_for_mouse = FALSE;
#endif

    if (!term_initialised)
	return;

    if (term_suspended) {
	if (term->resume) {
	    FPRINTF((stderr, "- calling term->resume()\n"));
	    (*term->resume) ();
	}
	term_suspended = FALSE;
    }
    if (term_graphics) {
	(*term->text) ();
	term_graphics = FALSE;
    }
    if (term_initialised) {
	(*term->reset) ();
	term_initialised = FALSE;
#ifdef PM3D
	/* switch off output to special postscript file (if used) */
	postscript_gpoutfile = 0;
#endif
    }
}

void
term_apply_lp_properties(lp)
struct lp_style_type *lp;
{
    /*  This function passes all the line and point properties to the
     *  terminal driver and issues the corresponding commands.
     *
     *  Alas, sometimes it might be necessary to give some help to
     *  this function by explicitly issuing additional '(*term)(...)'
     *  commands.
     */

    if (lp->pointflag) {
	/* change points, too
	 * Currently, there is no 'pointtype' function.  For points
	 * there is a special function also dealing with (x,y) co-
	 * ordinates.
	 */
	(*term->pointsize) (lp->p_size);
    }
    /*  _first_ set the line width, _then_ set the line type !

     *  The linetype might depend on the linewidth in some terminals.
     */
    (*term->linewidth) (lp->l_width);
    (*term->linetype) (lp->l_type);
}



void
term_check_multiplot_okay(f_interactive)
TBOOLEAN f_interactive;
{
    FPRINTF((stderr, "term_multiplot_okay(%d)\n", f_interactive));

    if (!term_initialised)
	return;			/* they've not started yet */

    /* make sure that it is safe to issue an interactive prompt
     * it is safe if
     *   it is not an interactive read, or
     *   the terminal supports interactive multiplot, or
     *   we are not writing to stdout and terminal doesn't
     *     refuse multiplot outright
     */
    if (!f_interactive || (term->flags & TERM_CAN_MULTIPLOT) ||
	((gpoutfile != stdout) && !(term->flags & TERM_CANNOT_MULTIPLOT))
	) {
	/* it's okay to use multiplot here, but suspend first */
	term_suspend();
	return;
    }
    /* uh oh : they're not allowed to be in multiplot here */

    term_end_multiplot();

    /* at this point we know that it is interactive and that the
     * terminal can either only do multiplot when writing to
     * to a file, or it does not do multiplot at all
     */

    if (term->flags & TERM_CANNOT_MULTIPLOT)
	int_error(NO_CARET, "This terminal does not support multiplot");
    else
	int_error(NO_CARET, "Must set output to a file or put all multiplot commands on one input line");
}


void
write_multiline(x, y, text, hor, vert, angle, font)
    unsigned int x, y;
    char *text;
    JUSTIFY hor;		/* horizontal ... */
    VERT_JUSTIFY vert;		/* ... and vertical just - text in hor direction despite angle */
    int angle;			/* assume term has already been set for this */
    const char *font;		/* NULL or "" means use default */
{
    register struct termentry *t = term;
    char *p = text;

    if (!p)
	return;

    /* EAM 9-Feb-2003 - Set font before calculating sizes */
    if (font && *font)
	(*t->set_font) (font);

    if (vert != JUST_TOP) {
	/* count lines and adjust y */
	int lines = 0;		/* number of linefeeds - one fewer than lines */
	while (*p++) {
	    if (*p == '\n')
		++lines;
	}
	if (angle)
	    x -= (vert * lines * t->v_char) / 2;
	else
	    y += (vert * lines * t->v_char) / 2;
    }

    for (;;) {			/* we will explicitly break out */

	if ((text != NULL) && (p = strchr(text, '\n')) != NULL)
	    *p = 0;		/* terminate the string */

	if ((*t->justify_text) (hor)) {
	    (*t->put_text) (x, y, text);
	} else {
	    int fix = hor * (t->h_char) * strlen(text) / 2;
	    if (angle)
		(*t->put_text) (x, y - fix, text);
	    else
		(*t->put_text) (x - fix, y, text);
	}
	if (angle == TEXT_VERTICAL)
	    x += t->v_char;
	else if (-angle == TEXT_VERTICAL)
	    x -= t->v_char;
	else
	    y -= t->v_char;

	if (!p)
	    break;
	else {
	    /* put it back */
	    *p = '\n';
	}

	text = p + 1;
    }				/* unconditional branch back to the for(;;) - just a goto ! */

    if (font && *font)
	(*t->set_font) ("");

}


static void
do_point(x, y, number)
unsigned int x, y;
int number;
{
    register int htic, vtic;
    register struct termentry *t = term;

    if (number < 0) {		/* do dot */
	(*t->move) (x, y);
	(*t->vector) (x, y);
	return;
    }
    number %= POINT_TYPES;
    /* should be in term_tbl[] in later version */
    htic = (term_pointsize * t->h_tic / 2);
    vtic = (term_pointsize * t->v_tic / 2);

    /* point types 1..4 are same as in postscript, png and x11
       point types 5..6 are "similar"
       (note that (number) equals (pointtype-1)
    */
    switch (number) {
    case 4:			/* do diamond */
	(*t->move) (x - htic, y);
	(*t->vector) (x, y - vtic);
	(*t->vector) (x + htic, y);
	(*t->vector) (x, y + vtic);
	(*t->vector) (x - htic, y);
	(*t->move) (x, y);
	(*t->vector) (x, y);
	break;
    case 0:			/* do plus */
	(*t->move) (x - htic, y);
	(*t->vector) (x - htic, y);
	(*t->vector) (x + htic, y);
	(*t->move) (x, y - vtic);
	(*t->vector) (x, y - vtic);
	(*t->vector) (x, y + vtic);
	break;
    case 3:			/* do box */
	(*t->move) (x - htic, y - vtic);
	(*t->vector) (x - htic, y - vtic);
	(*t->vector) (x + htic, y - vtic);
	(*t->vector) (x + htic, y + vtic);
	(*t->vector) (x - htic, y + vtic);
	(*t->vector) (x - htic, y - vtic);
	(*t->move) (x, y);
	(*t->vector) (x, y);
	break;
    case 1:			/* do X */
	(*t->move) (x - htic, y - vtic);
	(*t->vector) (x - htic, y - vtic);
	(*t->vector) (x + htic, y + vtic);
	(*t->move) (x - htic, y + vtic);
	(*t->vector) (x - htic, y + vtic);
	(*t->vector) (x + htic, y - vtic);
	break;
    case 5:			/* do triangle */
	(*t->move) (x, y + (4 * vtic / 3));
	(*t->vector) (x - (4 * htic / 3), y - (2 * vtic / 3));
	(*t->vector) (x + (4 * htic / 3), y - (2 * vtic / 3));
	(*t->vector) (x, y + (4 * vtic / 3));
	(*t->move) (x, y);
	(*t->vector) (x, y);
	break;
    case 2:			/* do star */
	(*t->move) (x - htic, y);
	(*t->vector) (x - htic, y);
	(*t->vector) (x + htic, y);
	(*t->move) (x, y - vtic);
	(*t->vector) (x, y - vtic);
	(*t->vector) (x, y + vtic);
	(*t->move) (x - htic, y - vtic);
	(*t->vector) (x - htic, y - vtic);
	(*t->vector) (x + htic, y + vtic);
	(*t->move) (x - htic, y + vtic);
	(*t->vector) (x - htic, y + vtic);
	(*t->vector) (x + htic, y - vtic);
	break;
    }
}

static void
do_pointsize(size)
double size;
{
    term_pointsize = (size >= 0 ? size : 1);
}


/*
 * general point routine
 */
static void
line_and_point(x, y, number)
unsigned int x, y;
int number;
{
    /* temporary(?) kludge to allow terminals with bad linetypes 
       to make nice marks */

    (*term->linetype) (NICE_LINE);
    do_point(x, y, number);
}

/* 
 * general arrow routine
 *
 * I set the angle between the arrowhead and the line 15 degree.
 * The length of arrowhead varies depending on the line length 
 * within the the range [0.3*(the-tic-length), 2*(the-tic-length)].
 * No head is printed if the arrow length is zero.
 *
 *            Yasu-hiro Yamazaki(hiro@rainbow.physics.utoronto.ca)
 *            Jul 1, 1993
 */

#define COS15 (0.96593)		/* cos of 15 degree */
#define SIN15 (0.25882)		/* sin of 15 degree */

#define HEAD_LONG_LIMIT  (2.0)	/* long  limit of arrowhead length */
#define HEAD_SHORT_LIMIT (0.3)	/* short limit of arrowhead length */
				/* their units are the "tic" length */

#define HEAD_COEFF  (0.3)	/* default value of head/line length ratio */

int curr_arrow_headlength; /* access head length + angle without changing API */
double curr_arrow_headangle;	/* angle in degrees */
double curr_arrow_headbackangle;  /* angle in degrees */
int curr_arrow_headfilled;	/* arrow head filled or not */

static void
do_arrow(sx, sy, ex, ey, head)
    unsigned int sx, sy;	/* start point */
    unsigned int ex, ey;	/* end point (point of arrowhead) */
    int head;
{
    register struct termentry *t = term;
    float len_tic = ((double) (t->h_tic + t->v_tic)) / 2.0;
    /* average of tic sizes */
    /* (dx,dy) : vector from end to start */
    double dx = (double) sx - (double) ex;
    double dy = (double) sy - (double) ey;
    double len_arrow = sqrt(dx * dx + dy * dy);
#ifdef PM3D
    gpiPoint filledhead[5];
#endif
    int xm = 0, ym = 0;

    /* Calculate and draw arrow heads.
     * Draw no head for arrows with length = 0, or, to be more specific,
     * length < DBL_EPSILON, because len_arrow will almost always be != 0.
     */
    if (head && fabs(len_arrow) >= DBL_EPSILON) {
	int x1, y1, x2, y2;
	if (curr_arrow_headlength <= 0) {
	    /* arrow head with the default size */
	    /* now calc the head_coeff */
	    double coeff_shortest = len_tic * HEAD_SHORT_LIMIT / len_arrow;
	    double coeff_longest = len_tic * HEAD_LONG_LIMIT / len_arrow;
	    double head_coeff = GPMAX(coeff_shortest,
				      GPMIN(HEAD_COEFF, coeff_longest));
	    /* we put the arrowhead marks at 15 degrees to line */
	    x1 = (int) ((COS15 * dx - SIN15 * dy) * head_coeff);
	    y1 = (int) ((SIN15 * dx + COS15 * dy) * head_coeff);
	    x2 = (int) ((COS15 * dx + SIN15 * dy) * head_coeff);
	    y2 = (int) ((-SIN15 * dx + COS15 * dy) * head_coeff);
	    /* backangle defaults to 90 deg */
	    xm = (int) ((x1 + x2)/2);
	    ym = (int) ((y1 + y2)/2);
	} else {
	    /* the arrow head with the length + angle specified explicitly */
	    double alpha = curr_arrow_headangle * DEG2RAD;
	    double beta = curr_arrow_headbackangle * DEG2RAD;
	    double phi = atan2(-dy,-dx); /* azimuthal angle of the vector */
	    double backlen = curr_arrow_headlength * sin(alpha) / sin(beta);
	    double dx2, dy2;
	    /* anticlock-wise head segment */
	    x1 = -(int)(curr_arrow_headlength * cos( alpha - phi ));
	    y1 =  (int)(curr_arrow_headlength * sin( alpha - phi ));
	    /* clock-wise head segment */
	    dx2 = -curr_arrow_headlength * cos( phi + alpha );
	    dy2 = -curr_arrow_headlength * sin( phi + alpha );
	    x2 = (int) (dx2);
	    y2 = (int) (dy2);
	    /* back point */
	    xm = (int) (dx2 + backlen * cos( phi + beta ));
	    ym = (int) (dy2 + backlen * sin( phi + beta ));
	}
#ifdef PM3D
	if (curr_arrow_headfilled==2) {
	    /* draw filled forward arrow head */
	    filledhead[0].x = ex + xm;
	    filledhead[0].y = ey + ym;
	    filledhead[1].x = ex + x1;
	    filledhead[1].y = ey + y1;
	    filledhead[2].x = ex;
	    filledhead[2].y = ey;
	    filledhead[3].x = ex + x2;
	    filledhead[3].y = ey + y2;
	    filledhead[4].x = ex + xm;
	    filledhead[4].y = ey + ym;
	    (*t->filled_polygon) (5, filledhead);
	}
#endif
	/* draw outline of forward arrow head */
	if (curr_arrow_headfilled!=0) {
	    (*t->move) (ex + xm, ey + ym);
	    (*t->vector) (ex + x1, ey + y1);
	    (*t->vector) (ex, ey);
	    (*t->vector) (ex + x2, ey + y2);
	    (*t->vector) (ex + xm, ey + ym);
	} else {
	    (*t->move) (ex + x1, ey + y1);
	    (*t->vector) (ex, ey);
	    (*t->vector) (ex + x2, ey + y2);
	}
	if (head == 2) { /* backward arrow head */
#ifdef PM3D
	    if (curr_arrow_headfilled==2) {
		/* draw filled backward arrow head */
		filledhead[0].x = sx - xm;
		filledhead[0].y = sy - ym;
		filledhead[1].x = sx - x1;
		filledhead[1].y = sy - y1;
		filledhead[2].x = sx;
		filledhead[2].y = sy;
		filledhead[3].x = sx - x2;
		filledhead[3].y = sy - y2;
		filledhead[4].x = sx - xm;
		filledhead[4].y = sy - ym;
		(*t->filled_polygon) (5, filledhead);
	    }
#endif
	    /* draw outline of backward arrow head */
	    if (curr_arrow_headfilled!=0) {
		(*t->move) ( sx - xm, sy - ym);
		(*t->vector) ( sx - x2, sy - y2);
		(*t->vector) (sx, sy);
		(*t->vector) (sx - x1, sy - y1);
		(*t->vector) ( sx - xm, sy - ym);
	    } else {
		(*t->move) ( sx - x2, sy - y2);
		(*t->vector) (sx, sy);
		(*t->vector) (sx - x1, sy - y1);
	    }
	}
    }
    /* Draw the line for the arrow. */
    if ( (head == 2) && 
	 (fabs(len_arrow) >= DBL_EPSILON) && (curr_arrow_headfilled!=0) )
	(*t->move) (sx - xm, sy - ym);
    else
	(*t->move) (sx, sy);
    if ( head && 
	 (fabs(len_arrow) >= DBL_EPSILON) && (curr_arrow_headfilled!=0) )
	(*t->vector) (ex + xm, ey + ym);
    else
	(*t->vector) (ex, ey);
}

#define TERM_PROTO
#define TERM_BODY
#define TERM_PUBLIC static

#include "term.h"

#undef TERM_PROTO
#undef TERM_BODY
#undef TERM_PUBLIC


/* Dummy functions for unavailable features */
/* return success if they asked for default - this simplifies code
 * where param is passed as a param. Client can first pass it here,
 * and only if it fails do they have to see what was trying to be done
 */

/* change angle of text.  0 is horizontal left to right.
   * 1 is vertical bottom to top (90 deg rotate)  
 */
static int
null_text_angle(ang)
int ang;
{
    return (ang == 0);
}

/* change justification of text.  
 * modes are LEFT (flush left), CENTRE (centred), RIGHT (flush right)
 */
static int
null_justify_text(just)
enum JUSTIFY just;
{
    return (just == LEFT);
}


/* Change scale of plot.
 * Parameters are x,y scaling factors for this plot.
 * Some terminals (eg latex) need to do scaling themselves.
 */
static int
null_scale(x, y)
    double x, y;
{
    (void) x;			/* avoid -Wunused warning */
    (void) y;
    return FALSE;		/* can't be done */
}

/* HBB 990829: unused --> commented out */
#if 0
int
do_scale(x, y)
double x;
double y;
{
    return TRUE;		/* can be done */
}
#endif /* commented out */

static void
options_null()
{
    term_options[0] = '\0';	/* we have no options */
}

static void
UNKNOWN_null()
{
}

static void
MOVE_null(x, y)
    unsigned int x, y;
{
    (void) x;			/* avoid -Wunused warning */
    (void) y;
}

static void
LINETYPE_null(t)
    int t;
{
    (void) t;			/* avoid -Wunused warning */
}

static void
PUTTEXT_null(x, y, s)
    unsigned int x, y;
    const char *s;
{
    (void) s;			/* avoid -Wunused warning */
    (void) x;
    (void) y;
}


static int
set_font_null(s)
    const char *s;
{
    (void) s;			/* avoid -Wunused warning */
    return FALSE;
}

static void
null_linewidth(s)
    double s;
{
    (void) s;			/* avoid -Wunused warning */
}


/* cast to get rid of useless warnings about UNKNOWN_null */
/* FIXME HBB 20010527: not used anywhere! */
typedef void (*void_fp) __PROTO((void));


/* setup the magic macros to compile in the right parts of the
 * terminal drivers included by term.h
 */

#define TERM_TABLE
#define TERM_TABLE_START(x) ,{
#define TERM_TABLE_END(x)   }


/*
 * term_tbl[] contains an entry for each terminal.  "unknown" must be the
 *   first, since term is initialized to 0.
 */
static struct termentry term_tbl[] =
{
    {"unknown", "Unknown terminal type - not a plotting device",
     100, 100, 1, 1,
     1, 1, options_null, UNKNOWN_null, UNKNOWN_null,
     UNKNOWN_null, null_scale, UNKNOWN_null, MOVE_null, MOVE_null,
     LINETYPE_null, PUTTEXT_null}
    ,
    {"table", "Dump ASCII table of X Y [Z] values to output",
     100, 100, 1, 1,
     1, 1, options_null, UNKNOWN_null, UNKNOWN_null,
     UNKNOWN_null, null_scale, UNKNOWN_null, MOVE_null, MOVE_null,
     LINETYPE_null, PUTTEXT_null}
#include "term.h"

};

#define TERMCOUNT (sizeof(term_tbl)/sizeof(term_tbl[0]))

/* mainly useful for external code */
GP_INLINE int
term_count()
{
    return TERMCOUNT;
}

void
list_terms()
{
    register int i;
    char *line_buffer = gp_alloc(BUFSIZ, "list_terms");
    int sort_idxs[TERMCOUNT];

    /* sort terminal types alphabetically */
    for( i = 0; i < TERMCOUNT; i++ )
	sort_idxs[i] = i;
    qsort( sort_idxs, TERMCOUNT, sizeof(int), termcomp );
    /* now sort_idxs[] contains the sorted indices */
    
    StartOutput();
    strcpy(line_buffer, "\nAvailable terminal types:\n");
    OutLine(line_buffer);

    for (i = 0; i < TERMCOUNT; i++) {
	sprintf(line_buffer, "  %15s  %s\n",
		term_tbl[sort_idxs[i]].name,
                term_tbl[sort_idxs[i]].description);
	OutLine(line_buffer);
    }

    EndOutput();
    free(line_buffer);
}

static int
termcomp(arga, argb)
    const generic *arga, *argb;
{
    const int *a = arga;
    const int *b = argb;

    return( strcasecmp( term_tbl[*a].name, term_tbl[*b].name ) );
}

/* set_term: get terminal number from name on command line
 * will change 'term' variable if successful
 */
struct termentry *
set_term(c_token_arg)
int c_token_arg;
{
    register struct termentry *t = NULL;
    char *input_name;

    if (!token[c_token_arg].is_token)
	int_error(c_token_arg, "terminal name expected");
    input_name = input_line + token[c_token_arg].start_index;
    t = change_term(input_name, token[c_token_arg].length);
    if (!t)
	int_error(c_token_arg, "unknown or ambiguous terminal type; type just 'set terminal' for a list");

    /* otherwise the type was changed */

    return (t);
}

/* change_term: get terminal number from name and set terminal type
 *
 * returns NULL for unknown or ambiguous, otherwise is terminal
 * driver pointer
 */
struct termentry *
change_term(name, length)
const char *name;
int length;
{
    int i;
    struct termentry *t = NULL;

    for (i = 0; i < TERMCOUNT; i++) {
	if (!strncmp(name, term_tbl[i].name, length)) {
	    if (t)
		return (NULL);	/* ambiguous */
	    t = term_tbl + i;
	}
    }

    if (!t)			/* unknown */
	return (NULL);

    /* Success: set terminal type now */

    term = t;
    term_initialised = FALSE;
    name = term->name;

    if (term->scale != null_scale)
	fputs("Warning : scale interface is not null_scale - may not work with multiplot\n", stderr);

    /* check that optional fields are initialised to something */
    if (term->text_angle == 0)
	term->text_angle = null_text_angle;
    if (term->justify_text == 0)
	term->justify_text = null_justify_text;
    if (term->point == 0)
	term->point = do_point;
    if (term->arrow == 0)
	term->arrow = do_arrow;
    if (term->set_font == 0)
	term->set_font = set_font_null;
    if (term->pointsize == 0)
	term->pointsize = do_pointsize;
    if (term->linewidth == 0)
	term->linewidth = null_linewidth;

    /* Special handling for unixplot term type */
    if (!strncmp("unixplot", name, 8)) {
	UP_redirect(2);		/* Redirect actual stdout for unixplots */
    } else if (unixplot) {
	UP_redirect(3);		/* Put stdout back together again. */
    }
    if (interactive)
	fprintf(stderr, "Terminal type set to '%s'\n", name);

    return (t);
}

#ifdef X11
int
x11driver_found()
{
  char *binname = "/gnuplot_x11";
  char *fullname;
  struct stat buf;
  
  fullname = (char*)malloc(sizeof(X11_DRIVER_DIR) + sizeof(binname) + 1);
  strcat(fullname, X11_DRIVER_DIR);
  strcat(fullname, binname);

  /* exists? */
  if (stat(fullname, &buf)) {
    free(fullname);
    return 0;
  }

  free(fullname);
  /* executable? */
  if (buf.st_mode && S_IXOTH)
    return 1;

  return 0;
}
#endif

/*
 * Routine to detect what terminal is being used (or do anything else
 * that would be nice).  One anticipated (or allowed for) side effect
 * is that the global ``term'' may be set. 
 * The environment variable GNUTERM is checked first; if that does
 * not exist, then the terminal hardware is checked, if possible, 
 * and finally, we can check $TERM for some kinds of terminals.
 * A default can be set with -DDEFAULTTERM=myterm in the Makefile
 * or #define DEFAULTTERM myterm in term.h
 */
/* thanks to osupyr!alden (Dave Alden) for the original GNUTERM code */
void
init_terminal()
{
    char *term_name = DEFAULTTERM;
#if (defined(__TURBOC__) && defined(MSDOS) && !defined(_Windows)) || defined(NEXT) || defined(SUN) || defined(X11)
    char *env_term = NULL;	/* from TERM environment var */
#endif
#ifdef X11
    char *display = NULL;
#endif
    char *gnuterm = NULL;

    /* GNUTERM environment variable is primary */
    gnuterm = getenv("GNUTERM");
    if (gnuterm != (char *) NULL) {
	term_name = gnuterm;
    } else {

#ifdef __ZTC__
	term_name = ztc_init();
#endif

#ifdef VMS
	term_name = vms_init();
#endif /* VMS */

#ifdef NEXT
	env_term = getenv("TERM");
	if (term_name == (char *) NULL
	    && env_term != (char *) NULL && strcmp(env_term, "next") == 0)
	    term_name = "next";
#endif /* NeXT */

#ifdef __BEOS__
	env_term = getenv("TERM");
	if (term_name == (char *) NULL
	    && env_term != (char *) NULL && strcmp(env_term, "beterm") == 0)
	    term_name = "be";
#endif /* BeOS */

#ifdef SUN
	env_term = getenv("TERM");	/* try $TERM */
	if (term_name == (char *) NULL
	    && env_term != (char *) NULL && strcmp(env_term, "sun") == 0)
	    term_name = "sun";
#endif /* SUN */

#ifdef _Windows
	term_name = "win";
#endif /* _Windows */

#ifdef GPR
	/* find out whether stdout is a DM pad. See term/gpr.trm */
	if (gpr_isa_pad())
	    term_name = "gpr";
#else
# ifdef APOLLO
	/* find out whether stdout is a DM pad. See term/apollo.trm */
	if (apollo_isa_pad())
	    term_name = "apollo";
# endif				/* APOLLO */
#endif /* GPR    */

#ifdef X11
	env_term = getenv("TERM");	/* try $TERM */
	if (term_name == (char *) NULL
	    && env_term != (char *) NULL && strcmp(env_term, "xterm") == 0)
	  term_name = "x11";
	display = getenv("DISPLAY");
	if (term_name == (char *) NULL && display != (char *) NULL)
	  term_name = "x11";
	if (X11_Display)
	  term_name = "x11";
	/* if x11 was selected check for driver */
	if (term_name && (strcmp(term_name, "x11") == 0) && !x11driver_found() && isatty(fileno(stdin))) {
	  printf("*** X11 output driver not found, switching to dumb terminal!\n");
	  printf("*** If you want to use the X11 output, please install the ""gnuplot-x11"" package\n");
	  term_name = "dumb";
	};      
#endif /* x11 */

#ifdef AMIGA
	term_name = "amiga";
#endif

#if defined(ATARI) || defined(MTOS)
	term_name = "atari";
#endif

#ifdef UNIXPC
	if (iswind() == 0) {
	    term_name = "unixpc";
	}
#endif /* unixpc */

#ifdef CGI
	if (getenv("CGIDISP") || getenv("CGIPRNT"))
	    term_name = "cgi";
#endif /*CGI */

#ifdef DJGPP
	term_name = "svga";
#endif

#ifdef GRASS
	term_name = "grass";
#endif

#ifdef OS2
/* amai: Note that we do some checks above and now overwrite any
   results. Perhaps we may disable checks above!? */
#ifdef X11
/* WINDOWID is set in sessions like xterm, etc.
   DISPLAY is also mandatory. */
	env_term = getenv("WINDOWID");
	display  = getenv("DISPLAY");
	if ((env_term != (char *) NULL) && (display != (char *) NULL))
	    term_name = "x11";
	else
#endif		/* X11 */
	    term_name = "pm";
#endif /*OS2 */

/* set linux terminal only if LINUX_setup was successfull, if we are on X11
   LINUX_setup has failed, also if we are logged in by network */
#ifdef LINUXVGA
	if (LINUX_graphics_allowed)
#ifdef VGAGL
	    term_name = "vgagl";
#else
	    term_name = "linux";
#endif
#endif /* LINUXVGA */
    }

    /* We have a name, try to set term type */
    if (term_name != NULL && *term_name != '\0') {
	if (change_term(term_name, (int) strlen(term_name)))
	    return;
	fprintf(stderr, "Unknown or ambiguous terminal name '%s'\n", term_name);
    }
    change_term("unknown", 7);
}


#ifdef __ZTC__
char *
ztc_init()
{
    int g_mode;
    char *term_name = NULL;

    g_mode = fg_init();

    switch (g_mode) {
    case FG_NULL:
	fputs("Graphics card not detected or not supported.\n", stderr);
	exit(1);
    case FG_HERCFULL:
	term_name = "hercules";
	break;
    case FG_EGAMONO:
	term_name = "egamono";
	break;
    case FG_EGAECD:
	term_name = "egalib";
	break;
    case FG_VGA11:
	term_name = "vgamono";
	break;
    case FG_VGA12:
	term_name = "vgalib";
	break;
    case FG_VESA6A:
	term_name = "svgalib";
	break;
    case FG_VESA5:
	term_name = "ssvgalib";
	break;
    }
    fg_term();
    return (term_name);
}
#endif /* __ZTC__ */


#if defined(UNIXPLOT) && !defined(GNUGRAPH)
static void
UP_redirect(caller)
int caller;
/*
 * Unixplot can't really write to gpoutfile--it wants to write to stdout.
 * This is normally ok, but the original design of gnuplot gives us
 * little choice.  Originally users of unixplot had to anticipate
 * their needs and redirect all I/O to a file...  Not very gnuplot-like.
 *
 * caller:  1 - called from SET OUTPUT "FOO.OUT"
 * 2 - called from SET TERM UNIXPLOT
 * 3 - called from SET TERM other
 * 4 - called from SET OUTPUT
 */
{
    switch (caller) {
    case 1:
	/* Don't save, just replace stdout w/gpoutfile (save was already done). */
	if (unixplot)
	    *(stdout) = *(gpoutfile);	/* Copy FILE structure */
	break;
    case 2:
	if (!unixplot) {
	    fflush(stdout);
	    save_stdout = *(stdout);
	    *(stdout) = *(gpoutfile);	/* Copy FILE structure */
	    unixplot = 1;
	}
	break;
    case 3:
	/* New terminal in use--put stdout back to original. */
	/* closepl(); */ /* This is called by the term. */
	fflush(stdout);
	*(stdout) = save_stdout;	/* Copy FILE structure */
	unixplot = 0;
	break;
    case 4:
	/*  User really wants to go to normal output... */
	if (unixplot) {
	    fflush(stdout);
	    *(stdout) = save_stdout;	/* Copy FILE structure */
	}
	break;
    }
}
#else /* !UNIXPLOT || GNUGRAPH */
/*
 * This is always defined so we don't have to have command.c know if it
 * is there or not.
 */
static void
UP_redirect(caller)
int caller;
{
    caller = caller;		/* to stop Turbo C complaining 
				   * about caller not being used */
}
#endif /* !UNIXPLOT || GNUGRAPH */


/* test terminal by drawing border and text */
/* called from command test */
void
test_term()
{
    register struct termentry *t = term;
    const char *str;
    int x, y, xl, yl, i;
    unsigned int xmax_t, ymax_t;
    char label[MAX_ID_LEN];
    int key_entry_height;
    int p_width;

    term_start_plot();
    screen_ok = FALSE;
    xmax_t = (unsigned int) (t->xmax * xsize);
    ymax_t = (unsigned int) (t->ymax * ysize);

    p_width = pointsize * (t->h_tic);
    key_entry_height = pointsize * (t->v_tic) * 1.25;
    if (key_entry_height < (t->v_char))
	key_entry_height = (t->v_char);

    /* border linetype */
    (*t->linewidth) (1.0);
    (*t->linetype) (LT_BLACK);
    (*t->move) (0, 0);
    (*t->vector) (xmax_t - 1, 0);
    (*t->vector) (xmax_t - 1, ymax_t - 1);
    (*t->vector) (0, ymax_t - 1);
    (*t->vector) (0, 0);
    (*t->linetype)(0);
    (void) (*t->justify_text) (LEFT);
    (*t->put_text) (t->h_char * 5, ymax_t - t->v_char * 1.5, "Terminal Test");
#ifdef USE_MOUSE
    if (t->set_ruler) {
	(*t->put_text) (t->h_char * 5, ymax_t - t->v_char * 3, "Mouse and hotkeys are supported, hit: h r m 6");
    }
#endif
    (*t->linetype)(LT_BLACK);
    (*t->linetype) (LT_AXIS);
    (*t->move) (xmax_t / 2, 0);
    (*t->vector) (xmax_t / 2, ymax_t - 1);
    (*t->move) (0, ymax_t / 2);
    (*t->vector) (xmax_t - 1, ymax_t / 2);
    /* test width and height of characters */
    (*t->linetype) (3);
    (*t->move) (xmax_t / 2 - t->h_char * 10, ymax_t / 2 + t->v_char / 2);
    (*t->vector) (xmax_t / 2 + t->h_char * 10, ymax_t / 2 + t->v_char / 2);
    (*t->vector) (xmax_t / 2 + t->h_char * 10, ymax_t / 2 - t->v_char / 2);
    (*t->vector) (xmax_t / 2 - t->h_char * 10, ymax_t / 2 - t->v_char / 2);
    (*t->vector) (xmax_t / 2 - t->h_char * 10, ymax_t / 2 + t->v_char / 2);
    (*t->put_text) (xmax_t / 2 - t->h_char * 10, ymax_t / 2,
		    "12345678901234567890");
    (*t->put_text) (xmax_t / 2 - t->h_char * 10, ymax_t / 2 + t->v_char * 1.4,
		    "test of character width:");
    (*t->linetype) (LT_BLACK);
    /* test justification */
    (void) (*t->justify_text) (LEFT);
    (*t->put_text) (xmax_t / 2, ymax_t / 2 + t->v_char * 6, "left justified");
    str = "centre+d text";
    if ((*t->justify_text) (CENTRE))
	(*t->put_text) (xmax_t / 2,
			ymax_t / 2 + t->v_char * 5, str);
    else
	(*t->put_text) (xmax_t / 2 - strlen(str) * t->h_char / 2,
			ymax_t / 2 + t->v_char * 5, str);
    str = "right justified";
    if ((*t->justify_text) (RIGHT))
	(*t->put_text) (xmax_t / 2,
			ymax_t / 2 + t->v_char * 4, str);
    else
	(*t->put_text) (xmax_t / 2 - strlen(str) * t->h_char,
			ymax_t / 2 + t->v_char * 4, str);
    /* test text angle */
    (*t->linetype)(1);
    str = "rotated ce+ntred text";
    if ((*t->text_angle) (TEXT_VERTICAL)) {
	if ((*t->justify_text) (CENTRE))
	    (*t->put_text) (t->v_char,
			    ymax_t / 2, str);
	else
	    (*t->put_text) (t->v_char,
			    ymax_t / 2 - strlen(str) * t->h_char / 2, str);
	(*t->justify_text) (LEFT);
	str = " rotated by +45 deg";
	(*t->text_angle)(45);
	(*t->put_text)(t->v_char * 3, ymax_t / 2, str);
	(*t->justify_text) (LEFT);
	str = " rotated by -45 deg";
	(*t->text_angle)(-45);
	(*t->put_text)(t->v_char * 2, ymax_t / 2, str);
#ifdef HAVE_GD_PNG
	if (!strcmp(t->name, "png") || !strcmp(t->name, "gif") || !strcmp(t->name, "jpeg")) {
	    (*t->text_angle)(0);
	    str = "this terminal supports text rotation only for truetype fonts";
	    (*t->put_text)(t->v_char * 2 + t->h_char * 4, ymax_t / 2 - t->v_char * 2, str);
	}
#endif
    } else {
	(void) (*t->justify_text) (LEFT);
	(*t->put_text) (t->h_char * 2, ymax_t / 2 - t->v_char * 2, "can't rotate text");
    }
    (void) (*t->justify_text) (LEFT);
    (void) (*t->text_angle) (0);
    (*t->linetype)(LT_BLACK);

    /* test tic size */
    (*t->linetype)(4);
    (*t->move) ((unsigned int) (xmax_t / 2 + t->h_tic * (1 + ticscale)), (unsigned int) ymax_t - 1);
    (*t->vector) ((unsigned int) (xmax_t / 2 + t->h_tic * (1 + ticscale)),
		  (unsigned int) (ymax_t - ticscale * t->v_tic));
    (*t->move) ((unsigned int) (xmax_t / 2), (unsigned int) (ymax_t - t->v_tic * (1 + ticscale)));
    (*t->vector) ((unsigned int) (xmax_t / 2 + ticscale * t->h_tic),
                  (unsigned int) (ymax_t - t->v_tic * (1 + ticscale)));
    /* HBB 19990530: changed this to use right-justification, if possible... */
    str = "show ticscale";
    if ((*t->justify_text) (RIGHT))
	(*t->put_text) ((unsigned int) (xmax_t / 2 - 1* t->h_char),
			(unsigned int) (ymax_t - (t->v_tic * 2 + t->v_char / 2)),
		    str);
    else
	(*t->put_text) ((unsigned int) (xmax_t / 2 - (strlen(str)+1)	 * t->h_char),
			(unsigned int) (ymax_t - (t->v_tic * 2 + t->v_char / 2)),
			str);
    (void) (*t->justify_text) (LEFT);
    (*t->linetype)(LT_BLACK);

    /* test line and point types */
    x = xmax_t - t->h_char * 6 - p_width;
    y = ymax_t - key_entry_height;
    (*t->pointsize) (pointsize);
    for (i = -2; y > key_entry_height; i++) {
	(*t->linetype) (i);
	/*      (void) sprintf(label,"%d",i);  Jorgen Lippert
	   lippert@risoe.dk */
	(void) sprintf(label, "%d", i + 1);
	if ((*t->justify_text) (RIGHT))
	    (*t->put_text) (x, y, label);
	else
	    (*t->put_text) (x - strlen(label) * t->h_char, y, label);
	(*t->move) (x + t->h_char, y);
	(*t->vector) (x + t->h_char * 4, y);
	if (i >= -1)
	    (*t->point) (x + t->h_char * 5 + p_width / 2, y, i);
	y -= key_entry_height;
    }

    /* test some arrows */
    (*t->linewidth) (1.0);
    (*t->linetype) (0);
    x = xmax_t / 3;
    y = ymax_t / 3;
    xl = t->h_tic * 5;
    yl = t->v_tic * 5;
    (*t->arrow) (x, y, x + xl, y, TRUE);
    (*t->arrow) (x, y, x + xl / 2, y + yl, TRUE);
    (*t->arrow) (x, y, x, y + yl, TRUE);
    (*t->arrow) (x, y, x - xl / 2, y + yl, FALSE);
    (*t->arrow) (x, y, x - xl, y, TRUE);
    (*t->arrow) (x, y, x - xl, y - yl, TRUE);
    (*t->arrow) (x, y, x, y - yl, TRUE);
    (*t->arrow) (x, y, x + xl, y - yl, TRUE);

    /* test line widths */
    (void) (*t->justify_text) (LEFT);
    xl = xmax_t / 10;
    yl = ymax_t / 25;
    x = xmax_t * .075;
    y = yl;
   
    for (i=1; i<7; i++) {
	(*t->linewidth) ((float)(i)); (*t->linetype)(LT_BLACK);
	(*t->move) (x, y); (*t->vector) (x+xl, y);
	sprintf(label,"  lw %1d%c",i,0);
	(*t->put_text) (x+xl, y, label);
	y += yl;
    }
    (*t->put_text) (x, y, "linewidth");

#ifdef USE_ULIG_FILLEDBOXES
    /* test fill patterns */
    x = xmax_t * 0.5;
    y = 0;
    xl = xmax_t / 40;
    yl = ymax_t / 8;
    (*t->linewidth) ((float)(1));
    (*t->linetype)(LT_BLACK);
    (*t->justify_text) (CENTRE);
    (*t->put_text)(x+xl*7, yl+t->v_char*1.5, "pattern fill");
    for (i=0; i<10; i++) {
	int style = ((i<<4) + FS_PATTERN);
	if (t->fillbox)
	    (*t->fillbox) ( style, x, y, xl, yl );
	(*t->move)  (x,y);
	(*t->vector)(x,y+yl);
	(*t->vector)(x+xl,y+yl);
	(*t->vector)(x+xl,y);
	(*t->vector)(x,y);
	sprintf(label,"%2d",i);
	(*t->put_text)(x+xl/2, y+yl+t->v_char*0.5, label);
	x += xl * 1.5;
    }
#endif

#ifdef PM3D
    {
    int cen_x = (int)(0.75 * xmax_t);
    int cen_y = (int)(0.83 * ymax_t);
    int radius = xmax_t / 20;
    (*t->linetype)(2);
    /* test pm3d -- filled_polygon(), but not set_color() */
    if (t->filled_polygon) {
#define NUMBER_OF_VERTICES 6
	int n = NUMBER_OF_VERTICES;
	gpiPoint corners[NUMBER_OF_VERTICES+1];
#undef  NUMBER_OF_VERTICES
	int i;
	for (i = 0; i < n; i++) {
	    corners[i].x = cen_x + radius * cos(2*M_PI*i/n);
	    corners[i].y = cen_y + radius * sin(2*M_PI*i/n);
	}
	corners[n].x = corners[0].x;
	corners[n].y = corners[0].y;
	term->filled_polygon(n+1, corners);
	str = "(color) filled polygon:";
    } else
	str = "filled polygons not supported";
    i = ((*t->justify_text) (CENTRE)) ? 0 : t->h_char * strlen(str) / 2;
    (*t->put_text) (cen_x + i, cen_y + radius + t->v_char * 0.5, str);
    (*t->linetype)(LT_BLACK);
    }
#endif
    term_end_plot();
}

#if 0
# if defined(MSDOS)||defined(g)||defined(MTOS)||defined(OS2)||defined(_Windows)||defined(DOS386)
/* output for some terminal types must be binary to stop non Unix computers
   changing \n to \r\n. 
   If the output is not STDOUT, the following code reopens gpoutfile 
   with binary mode. */
void
reopen_binary()
{
    if (outstr) {
	(void) fclose(gpoutfile);
#  ifdef _Windows
	if (!stricmp(outstr, "PRN")) {
	    /* use temp file for windows */
	    (void) strcpy(filename, win_prntmp);
	}
#  endif
	if ((gpoutfile = fopen(filename, "wb")) == (FILE *) NULL) {
	    if ((gpoutfile = fopen(filename, "w")) == (FILE *) NULL) {
		os_error(NO_CARET, "cannot reopen file with binary type; output unknown");
	    } else {
		os_error(NO_CARET, "cannot reopen file with binary type; output reset to ascii");
	    }
	}
#  if defined(__TURBOC__) && defined(MSDOS)
#   ifndef _Windows
	if (!stricmp(outstr, "PRN")) {
	    /* Put the printer into binary mode. */
	    union REGS regs;
	    regs.h.ah = 0x44;	/* ioctl */
	    regs.h.al = 0;	/* get device info */
	    regs.x.bx = fileno(gpoutfile);
	    intdos(&regs, &regs);
	    regs.h.dl |= 0x20;	/* binary (no ^Z intervention) */
	    regs.h.dh = 0;
	    regs.h.ah = 0x44;	/* ioctl */
	    regs.h.al = 1;	/* set device info */
	    intdos(&regs, &regs);
	}
#   endif			/* !_Windows */
#  endif			/* TURBOC && MSDOS */
    }
}

# endif				/* MSDOS || g || MTOS || ... */
#endif /* 0 */

#ifdef VMS
/* these are needed to modify terminal characteristics */
# ifndef VWS_XMAX
   /* avoid duplicate warning; VWS includes these */
#  include <descrip.h>
#  include <ssdef.h>
# endif				/* !VWS_MAX */
# include <iodef.h>
# include <ttdef.h>
# include <tt2def.h>
# include <dcdef.h>
# include <stat.h>
# include <fab.h>
/* If you use WATCOM C or a very strict ANSI compiler, you may have to 
 * delete or comment out the following 3 lines: */
# ifndef TT2$M_DECCRT3		/* VT300 not defined as of VAXC v2.4 */
#  define TT2$M_DECCRT3 0X80000000
# endif
static unsigned short chan;
static int old_char_buf[3], cur_char_buf[3];
$DESCRIPTOR(sysoutput_desc, "SYS$OUTPUT");

char *
vms_init()
/*
 *  Look first for decw$display (decterms do regis)
 *  Determine if we have a regis terminal
 * and save terminal characteristics
 */
{
    /* Save terminal characteristics in old_char_buf and
       initialise cur_char_buf to current settings. */
    int i;
    if (getenv("DECW$DISPLAY"))
	return ("x11");
    atexit(vms_reset);
    sys$assign(&sysoutput_desc, &chan, 0, 0);
    sys$qiow(0, chan, IO$_SENSEMODE, 0, 0, 0, old_char_buf, 12, 0, 0, 0, 0);
    for (i = 0; i < 3; ++i)
	cur_char_buf[i] = old_char_buf[i];
    sys$dassgn(chan);

    /* Test if terminal is regis */
    if ((cur_char_buf[2] & TT2$M_REGIS) == TT2$M_REGIS)
	return ("regis");
    return (NULL);
}

void
vms_reset()
/* set terminal to original state */
{
    int i;
    sys$assign(&sysoutput_desc, &chan, 0, 0);
    sys$qiow(0, chan, IO$_SETMODE, 0, 0, 0, old_char_buf, 12, 0, 0, 0, 0);
    for (i = 0; i < 3; ++i)
	cur_char_buf[i] = old_char_buf[i];
    sys$dassgn(chan);
}

void
term_mode_tek()
/* set terminal mode to tektronix */
{
    long status;
    if (gpoutfile != stdout)
	return;			/* don't modify if not stdout */
    sys$assign(&sysoutput_desc, &chan, 0, 0);
    cur_char_buf[0] = 0x004A0000 | DC$_TERM | (TT$_TEK401X << 8);
    cur_char_buf[1] = (cur_char_buf[1] & 0x00FFFFFF) | 0x18000000;

    cur_char_buf[1] &= ~TT$M_CRFILL;
    cur_char_buf[1] &= ~TT$M_ESCAPE;
    cur_char_buf[1] &= ~TT$M_HALFDUP;
    cur_char_buf[1] &= ~TT$M_LFFILL;
    cur_char_buf[1] &= ~TT$M_MECHFORM;
    cur_char_buf[1] &= ~TT$M_NOBRDCST;
    cur_char_buf[1] &= ~TT$M_NOECHO;
    cur_char_buf[1] &= ~TT$M_READSYNC;
    cur_char_buf[1] &= ~TT$M_REMOTE;
    cur_char_buf[1] |= TT$M_LOWER;
    cur_char_buf[1] |= TT$M_TTSYNC;
    cur_char_buf[1] |= TT$M_WRAP;
    cur_char_buf[1] &= ~TT$M_EIGHTBIT;
    cur_char_buf[1] &= ~TT$M_MECHTAB;
    cur_char_buf[1] &= ~TT$M_SCOPE;
    cur_char_buf[1] |= TT$M_HOSTSYNC;

    cur_char_buf[2] &= ~TT2$M_APP_KEYPAD;
    cur_char_buf[2] &= ~TT2$M_BLOCK;
    cur_char_buf[2] &= ~TT2$M_DECCRT3;
    cur_char_buf[2] &= ~TT2$M_LOCALECHO;
    cur_char_buf[2] &= ~TT2$M_PASTHRU;
    cur_char_buf[2] &= ~TT2$M_REGIS;
    cur_char_buf[2] &= ~TT2$M_SIXEL;
    cur_char_buf[2] |= TT2$M_BRDCSTMBX;
    cur_char_buf[2] |= TT2$M_EDITING;
    cur_char_buf[2] |= TT2$M_INSERT;
    cur_char_buf[2] |= TT2$M_PRINTER;
    cur_char_buf[2] &= ~TT2$M_ANSICRT;
    cur_char_buf[2] &= ~TT2$M_AVO;
    cur_char_buf[2] &= ~TT2$M_DECCRT;
    cur_char_buf[2] &= ~TT2$M_DECCRT2;
    cur_char_buf[2] &= ~TT2$M_DRCS;
    cur_char_buf[2] &= ~TT2$M_EDIT;
    cur_char_buf[2] |= TT2$M_FALLBACK;

    status = sys$qiow(0, chan, IO$_SETMODE, 0, 0, 0, cur_char_buf, 12, 0, 0, 0, 0);
    if (status == SS$_BADPARAM) {
	/* terminal fallback utility not installed on system */
	cur_char_buf[2] &= ~TT2$M_FALLBACK;
	sys$qiow(0, chan, IO$_SETMODE, 0, 0, 0, cur_char_buf, 12, 0, 0, 0, 0);
    } else {
	if (status != SS$_NORMAL)
	    lib$signal(status, 0, 0);
    }
    sys$dassgn(chan);
}

void
term_mode_native()
/* set terminal mode back to native */
{
    int i;
    if (gpoutfile != stdout)
	return;			/* don't modify if not stdout */
    sys$assign(&sysoutput_desc, &chan, 0, 0);
    sys$qiow(0, chan, IO$_SETMODE, 0, 0, 0, old_char_buf, 12, 0, 0, 0, 0);
    for (i = 0; i < 3; ++i)
	cur_char_buf[i] = old_char_buf[i];
    sys$dassgn(chan);
}

void
term_pasthru()
/* set terminal mode pasthru */
{
    if (gpoutfile != stdout)
	return;			/* don't modify if not stdout */
    sys$assign(&sysoutput_desc, &chan, 0, 0);
    cur_char_buf[2] |= TT2$M_PASTHRU;
    sys$qiow(0, chan, IO$_SETMODE, 0, 0, 0, cur_char_buf, 12, 0, 0, 0, 0);
    sys$dassgn(chan);
}

void
term_nopasthru()
/* set terminal mode nopasthru */
{
    if (gpoutfile != stdout)
	return;			/* don't modify if not stdout */
    sys$assign(&sysoutput_desc, &chan, 0, 0);
    cur_char_buf[2] &= ~TT2$M_PASTHRU;
    sys$qiow(0, chan, IO$_SETMODE, 0, 0, 0, cur_char_buf, 12, 0, 0, 0, 0);
    sys$dassgn(chan);
}

void
fflush_binary()
{
    typedef short int INT16;	/* signed 16-bit integers */
    register INT16 k;		/* loop index */
    if (gpoutfile != stdout) {
	/* Stupid VMS fflush() raises error and loses last data block
	   unless it is full for a fixed-length record binary file.
	   Pad it here with NULL characters. */
	for (k = (INT16) ((*gpoutfile)->_cnt); k > 0; --k)
	    putc('\0', gpoutfile);
	fflush(gpoutfile);
    }
}
#endif /* VMS */

/*
 * This is an abstraction of the enhanced text mode originally written
 * for the postscript terminal driver by David Denholm and Matt Heffron.
 * I have split out a terminal-independent recursive syntax-parser 
 * routine that can be shared by all drivers that want to add support
 * for enhanced text mode.
 *
 * A driver that wants to make use of this common framework must provide
 * three new entries in TERM_TABLE:
 *	void *enhanced_open   (char *fontname, double fontsize, double base,
 *	                       TBOOLEAN widthflag, TBOOLEAN showflag, 
 *	                       int overprint)
 *	void *enhanced_writec (char c)
 *	void *enhanced_flush  ()
 *
 * Each driver also has a separate ENHXX_put_text() routine that replaces
 * the normal (term->put_text) routine while in enhanced mode.
 * This routine must initialize the following globals used by the shared code:
 *	enhanced_fontscale	converts font size to device resolution units
 *	enhanced_escape_format	used to process octal escape characters \xyz
 *
 * I bent over backwards to make the output of the revised code identical
 * to the output of the original postscript version.  That means there is
 * some cruft left in here (enhanced_max_height for one thing, and all
 * the code relating to RememberFont) that is probably irrelevant to any 
 * new drivers using the code.
 *
 * Ethan A Merritt - November 2003
 */

#ifdef DEBUG_ENH
#define ENH_DEBUG(x) printf x;
#else
#define ENH_DEBUG(x)
#endif

static void
do_enh_writec(c)
    char c;
{
    *enhanced_cur_text++ = c;
}

/*
 * Process a bit of string, and return the last character used.
 * p is start of string
 * brace is TRUE to keep processing to }, FALSE to do one character only
 * fontname & fontsize are obvious
 * base is the current baseline
 * widthflag is TRUE if the width of this should count,
 *              FALSE for zero width boxes
 * showflag is TRUE if this should be shown,
 *             FALSE if it should not be shown (like TeX \phantom)
 * overprint is 0 for normal operation,
 *              1 for the underprinted text (included in width calculation),
 *              2 for the overprinted text (not included in width calc)
 *              (overprinted text is centered horizontally on underprinted text
 */

char *
enhanced_recursion(p, brace, fontname, fontsize, base, widthflag, showflag, overprint)
    char *p, *fontname;
    TBOOLEAN brace, widthflag, showflag;
    double fontsize, base;
    int overprint;
{

    ENH_DEBUG(("RECURSE WITH [%p] \"%s\", %d %s %.1f %.1f %d %d %d\n", p, p, brace, fontname, fontsize, base, widthflag, showflag, overprint));

/* Start each recursion with a clean string */
    (term->enhanced_flush)();

    if (base + fontsize > enhanced_max_height) {
	enhanced_max_height = base + fontsize;
	ENH_DEBUG(("Setting max height to %.1f\n", enhanced_max_height));
    }

    if (base < enhanced_min_height) {
	enhanced_min_height = base;
	ENH_DEBUG(("Setting min height to %.1f\n", enhanced_min_height));
    }

    while (*p) {
	float shift;

	switch (*p) {
	case '}'  :
	    /*{{{  deal with it*/
	    if (brace)
		return (p);

	    fputs("enhanced text parser - spurious }\n", stderr);
	    break;
	    /*}}}*/

	case '_'  :
	case '^'  :
	    /*{{{  deal with super/sub script*/
	    shift = (*p == '^') ? 0.5 : -0.3;
	    (term->enhanced_flush)();
	    p = enhanced_recursion(p + 1, FALSE, fontname, fontsize * 0.8,
			      base + shift * fontsize, widthflag,
			      showflag, overprint);
	    break;
	    /*}}}*/
	case '{'  :
	    {
		char *savepos = NULL, save = 0;
		char *localfontname = fontname, ch;
		int recode = 1;
		float f = fontsize, ovp;

		/*{{{  recurse (possibly with a new font) */

		ENH_DEBUG(("Dealing with {\n"));
	    
		/* get vertical offset (if present) for overprinted text */
		while (*++p == ' ');
		if (overprint == 2) {
		    ovp = (float)strtod(p,&p);
		    if (term->flags & TERM_IS_POSTSCRIPT)
			base = ovp*f;
		    else
			base += ovp*f;
		}
		--p;		/* HBB 20001021: bug fix: 10^{2} broken */

		if (*++p == '/') {
		    /* then parse a fontname, optional fontsize */
		    while (*++p == ' ')
			;	/* do nothing */
		    if (*p=='-') {
			recode = 0;
			while (*++p == ' ')
			    ;	/* do nothing */
		    }
		    localfontname = p;
		    while ((ch = *p) > ' ' && ch != '=' && ch != '*')
			++p;
		    save = *(savepos=p);
		    if (ch == '=') {
			*p++ = '\0';				
			/*{{{  get optional font size*/
			ENH_DEBUG(("Calling strtod(\"%s\") ...", p));
			f = (float)strtod(p, &p);
			ENH_DEBUG(("Returned %.1f and \"%s\"\n", f, p));

			if (f == 0)
			    f = fontsize;
			else
			    f *= enhanced_fontscale;  /* remember the scaling */

			ENH_DEBUG(("Font size %.1f\n", f));
			/*}}}*/
		    } else if (ch == '*') {
			*p++ = '\0';				
			/*{{{  get optional font size scale factor*/
			ENH_DEBUG(("Calling strtod(\"%s\") ...", p));
			f = (float)strtod(p, &p);
			ENH_DEBUG(("Returned %.1f and \"%s\"\n", f, p));

			if (f)
			    f *= fontsize;  /* apply the scale factor */
			else
			    f = fontsize;

			ENH_DEBUG(("Font size %.1f\n", f));
			/*}}}*/
		    } else {
			*p++ = '\0';
			f = fontsize;
		    }				

		    while (*p == ' ')
			++p;
		    if (! *localfontname) {
			localfontname = fontname;
		    } else if (!strncmp("postscript",term->name,9)) {
			/* FIXME - This cruft is left over from when the code */
			/* was part of post.trm.  No one else needs it!       */
			char *recodestring = (PS_RememberFont)(localfontname,
						 recode && !ENHps_opened_string);
			if (recode && recodestring) {
			    (term->enhanced_flush)();
			    fprintf(gpoutfile, "/%s %s",
				    localfontname, recodestring);
			}
		    }
		}
		/*}}}*/

		ENH_DEBUG(("Before recursing, we are at [%p] \"%s\"\n", p, p));

		p = enhanced_recursion(p, TRUE, localfontname, f, base,
				  widthflag, showflag, overprint);

		ENH_DEBUG(("BACK WITH \"%s\"\n", p));

		(term->enhanced_flush)();

		if (savepos)
		    /* restore overwritten character */
		    *savepos = save;
		break;
	    } /* case '{' */
	case '@' :
	    /*{{{  phantom box - prints next 'char', then restores currentpoint */
	    (term->enhanced_flush)();
	    (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, 3);
	    p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,
			      widthflag, showflag, overprint);
	    (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, 4);
	    break;
	    /*}}}*/

	case '&' :
	    /*{{{  character skip - skips space equal to length of character(s) */
	    (term->enhanced_flush)();

	    p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,
			      widthflag, FALSE, overprint);
	    break;
	    /*}}}*/

	case '~' :
	    /*{{{ overprinted text */
	    /* the second string is overwritten on the first, centered
	     * horizontally on the first and (optionally) vertically
	     * shifted by an amount specified (as a fraction of the
	     * current fontsize) at the beginning of the second string
	      
	     * Note that in this implementation neither the under- nor
	     * overprinted string can contain syntax that would result
	     * in additional recursions -- no subscripts,
	     * superscripts, or anything else, with the exception of a
	     * font definition at the beginning of the text */
	    
	    (term->enhanced_flush)();
	    p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,
			      widthflag, showflag, 1);
	    (term->enhanced_flush)();
	    p = enhanced_recursion(++p, FALSE, fontname, fontsize, base,
			      FALSE, showflag, 2);
		
	    overprint = 0;   /* may not be necessary, but just in case . . . */
	    break;
	    /*}}}*/

	case '('  :
	case ')'  :
	    /*{{{  an escape and print it */
	    /* special cases */
	    (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);
	    if (term->flags & TERM_IS_POSTSCRIPT)
		(term->enhanced_writec)('\\');
	    (term->enhanced_writec)(*p);
	    break;
	    /*}}}*/

	case '\\'  :
	    if (p[1]=='\\' || p[1]=='(' || p[1]==')') {
		(term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);
		(term->enhanced_writec)('\\');

	    /*{{{  The enhanced mode always uses \xyz as an octal character representation
	    	   but each terminal type must give us the actual output format wanted.
		   pdf.trm wants the raw character code, which is why we use strtol();
		   most other terminal types want some variant of "\\%o". */
	    } else if (p[1] >= '0' && p[1] <= '7') {
		char *e, escape[16], octal[4] = {'\0','\0','\0','\0'};
		
		(term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);
		octal[0] = *(++p);
		if (p[1] >= '0' && p[1] <= '7') {
		    octal[1] = *(++p);
		    if (p[1] >= '0' && p[1] <= '7')
			octal[2] = *(++p);
		}
		sprintf(escape, enhanced_escape_format, strtol(octal,NULL,8));
		for (e=escape; *e; e++) {
		    (term->enhanced_writec)(*e);
		}
		break;
	    }
	    ++p;

	    /* HBB 20030122: Avoid broken output if there's a \
	     * exactly at the end of the line */
	    if (*p == '\0') {
		fputs("enhanced text parser -- spurious backslash\n", stderr);
		break;
	    }

	    /* just go and print it (fall into the 'default' case) */
	    /*}}}*/
	default:
	    /*{{{  print it */
	    (term->enhanced_open)(fontname, fontsize, base, widthflag, showflag, overprint);
	    (term->enhanced_writec)(*p);
	    /*}}}*/
	} /* switch (*p) */

	/* like TeX, we only do one character in a recursion, unless it's
	 * in braces
	 */

	if (!brace) {
	    (term->enhanced_flush)();
	    return(p);  /* the ++p in the outer copy will increment us */
	}

	if (*p) /* only not true if { not terminated, I think */
	    ++p;	
    } /* while (*p) */

    (term->enhanced_flush)();
    return p;
}

/* Called after the end of recursion to check for errors */
static void
enh_err_check( str )
    const char *str;
{
    if (*str == '}')
	fputs("enhanced text mode parser - ignoring spurious }\n", stderr);
    else
	fprintf(stderr, "enhanced text mode parsing error - *str=0x%x\n", *str);
}