File: context.trm

package info (click to toggle)
gnuplot5 5.0.0~rc%2Bdfsg2-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 11,548 kB
  • ctags: 8,104
  • sloc: ansic: 77,108; cpp: 6,848; makefile: 1,932; sh: 1,343; lisp: 657; perl: 302; awk: 235; pascal: 194; tcl: 88; python: 46
file content (2122 lines) | stat: -rw-r--r-- 74,916 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
/*
 * $Id: context.trm,v 1.9 2014/01/30 05:50:52 sfeam Exp $
 */

/* GNUPLOT - context.trm */

/*[
 * Copyright (c) 2006-2011, Mojca Miklavec
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
]*/

/*
 * AUTHORS:
 *   Mojca Miklavec
 *       <mojca.miklavec.lists at gmail.com>
 *     - author of this file
 *     - improvements to m-gnuplot.tex
 *     - mp-gnuplot.mp - metapost macros to support gnuplot-specifics
 *       inside ConTeXt
 *
 *   Hans Hagen (author of ConTeXt)
 *        <pragma at wxs.nl>
 *      - a lot of functionality added to ConTeXt to enable better support
 *        of Gnuplot module, many bugs fixed
 *      - author of the module m-gnuplot.tex to support inclusion of Gnuplot
 *        graphics into ConTeXt
 *      - constant support on the most tricky issues
 *   Taco Hoekwater (developer of MetaPost, pdfTeX & LuaTeX)
 *        <taco at elvenkind.com>
 *      - some code of this file, many tricks, lots of bug fixes,
 *        suggestions and testing
 *      - Hans's right hand in ConTeXt development:
 *        constant support on even more tricky issues
 *
 *   For questions, suggestions, comments, improvements please contact:
 *     - Mojca Miklavec <mojca.miklavec.lists at gmail.com> or
 *     - <gnuplot-context at googlegroups.com>
 *     - http://wiki.contextgarden.net/Gnuplot
 *
 * With special thanks to:
 * - Peter Münster (ctx) for the initiative
 * - Renaud Aubin (ctx) for maintaining the first source code repository
 * - Aditya Mahajan (ctx) for some tricky parts in m-gnuplot.tex
 * - Timothée Lecomte & Ethan A Merritt (gnuplot) for many suggestion about improving this terminal
 * - Bastian Märkisch (gnuplot) for code improvements
 *
 */

/*
 * GNUPLOT -- context.trm
 *
 * This driver creates a ConTeXt document with embded metapost (metafun)
 * commands and is consequently used for creation of PDF documents.
 *
 * It is in a way similar to pslatex, but specialized for ConTeXt,
 * where it can also be used in the following way:
 *
 * \usemodule[gnuplot]
 *
 * \starttext
 * \title{Drawing nice graphs with \sc gnuplot}
 * \startGNUPLOTscript{sin}
 * plot sin(x) t '$\sin(x)$'
 * \stopGNUPLOTscript
 * \useGNUPLOTgraphic[sin]
 * \stoptext
 *
 * For more information see http://wiki.contextgarden.net/Gnuplot
 *
 * Mostly based on:
 * - default settings copied from LaTeX terminal (because I liked it)
 * - path construction & drawing routines from MetaPost terminal
 * - advanced functionality with reference to PostScript terminal
 *
 * Future plans:
 * - most important
 *   - different syntax for font switching
 *   - improve support for (transparent) binary images
 * - add missing functionality:
 *   - improved support for palettes
 *   - smooth shading in color bars
 *   - gouraud shading (if it will be implemented in gnuplot)
 *   - other color spaces
 * - derive a better metapost terminal out of this one (to replace the old one)
 */

#include "driver.h"
#include "pm3d.h"

#ifdef TERM_REGISTER
register_term(context)
#endif

#ifdef TERM_PROTO
TERM_PUBLIC void CONTEXT_options __PROTO((void));
TERM_PUBLIC void CONTEXT_init __PROTO((void));
TERM_PUBLIC void CONTEXT_reset __PROTO((void));
TERM_PUBLIC void CONTEXT_text __PROTO((void));
TERM_PUBLIC void CONTEXT_graphics __PROTO((void));
TERM_PUBLIC void CONTEXT_move __PROTO((unsigned int x, unsigned int y));
TERM_PUBLIC void CONTEXT_vector __PROTO((unsigned int x, unsigned int y));
TERM_PUBLIC void CONTEXT_linetype __PROTO((int lt));
TERM_PUBLIC void CONTEXT_put_text __PROTO((unsigned int x, unsigned int y, const char *str));

TERM_PUBLIC  int CONTEXT_text_angle __PROTO((int ang));
TERM_PUBLIC  int CONTEXT_justify_text __PROTO((enum JUSTIFY mode));
TERM_PUBLIC void CONTEXT_point __PROTO((unsigned int x, unsigned int y, int number));
TERM_PUBLIC void CONTEXT_arrow __PROTO((unsigned int sx, unsigned int sy, unsigned int ex, unsigned int ey, int head));
TERM_PUBLIC  int CONTEXT_set_font __PROTO((const char *font)); /* "font,size" */
TERM_PUBLIC void CONTEXT_pointsize __PROTO((double pointsize));
TERM_PUBLIC void CONTEXT_fillbox __PROTO((int style, unsigned int x1, unsigned int y1, unsigned int width, unsigned int height)); /* clear part of multiplot */
TERM_PUBLIC void CONTEXT_fill __PROTO((int style));
TERM_PUBLIC void CONTEXT_linewidth __PROTO((double linewidth));
TERM_PUBLIC  int CONTEXT_make_palette __PROTO((t_sm_palette *palette));
/* TERM_PUBLIC void CONTEXT_previous_palette __PROTO((void)); do we need it? */
TERM_PUBLIC void CONTEXT_set_color __PROTO((t_colorspec *colorspec));
TERM_PUBLIC void CONTEXT_filled_polygon __PROTO((int points, gpiPoint *corners));
TERM_PUBLIC void CONTEXT_image __PROTO((unsigned, unsigned, coordval *, gpiPoint *, t_imagecolor));

/* Metapost < 1.750 can only deal with numbers between 2^{-16} and 2^12=4069 */
/* scale is 1cm = 1000 units */

#define CONTEXT_DPCM 1000
#define CONTEXT_DPI (2.54 * CONTEXT_DPCM)
/* default plot size will be 5in x 3in */
#define CONTEXT_XSIZE_VALUE 5
#define CONTEXT_YSIZE_VALUE 3
#define CONTEXT_SIZE_UNIT INCHES
#define CONTEXT_XMAX (CONTEXT_XSIZE_VALUE * CONTEXT_DPI)
#define CONTEXT_YMAX (CONTEXT_YSIZE_VALUE * CONTEXT_DPI)
/* default fontsize: 12pt */
#define CONTEXT_FONTSIZE 12.0
/* default height of char: 12pt by default */
#define CONTEXT_VCHAR (CONTEXT_DPI * CONTEXT_FONTSIZE / 72.27)
/* in ConTeXt 12pt LM font is the default;
 * at that size digits are 5.8749847pt wide
 * in LaTeX, which assumes 11pt, the ratio is 5.3/11, which is similar */
#define CONTEXT_LM_H_TO_V_RATIO 0.4895
#define CONTEXT_HCHAR (CONTEXT_LM_H_TO_V_RATIO * CONTEXT_VCHAR)
/* default tic size: 3.5bp (chosen to suit the size of plot approximately)
 * - in LaTeX it is 5bp
 * - in TikZ it is 0.18cm (approximately 5.1bp)
 * - in PostScript it is 3.15pt
 * - MetaPost uses 5pt or 5bp
 */
#define CONTEXT_HTIC (3.5 * CONTEXT_DPI / 72)
#define CONTEXT_VTIC CONTEXT_HTIC

#endif /* TERM_PROTO */


#ifndef TERM_PROTO_ONLY
#ifdef TERM_BODY

/*
 * started counting when the code was included into CVS
 *
 * major number should change only in case of a complete rewrite or major incompatibility
 * minor number should change for every new functionality
 * patch number & date should change in every commit
 */
static const char CONTEXT_term_version[] = "1.0";
static const char CONTEXT_term_patch[]   = "0";
static const char CONTEXT_term_date[]    = "2011-11-05";

static void CONTEXT_params_reset __PROTO((void));

static void CONTEXT_adjust_dimensions __PROTO((void));
static void CONTEXT_fontstring_parse __PROTO((char *from_string, char *to_string, int to_size, double *fontsize));

static void CONTEXT_startpath __PROTO((void));
static void CONTEXT_endpath __PROTO((void));

static void CONTEXT_write_palette __PROTO((t_sm_palette *palette));
static void CONTEXT_write_palette_gradient __PROTO((gradient_struct *gradient, int cnt));

/* Each number is divided by 100 (1/100th of a point is drawn) */

static int CONTEXT_posx;
static int CONTEXT_posy;
/* remembers where we started the path:
 * if we finish it in the same point, the path is closed with --cycle
 * 
 * After I implemented this, the functionality has been added to gnuplot core
 * and PostScript terminal uses it, but to be on the safe side,
 * I prefer not to add last-minute patches which could potentially break something.
 * (the code written here proved to be rather safe & working so far)
 * In the next version the core functionality should be integrated & tested.
 */
static int CONTEXT_path_start_x;
static int CONTEXT_path_start_y;
/* fontname, fontsize */
static char CONTEXT_font[MAX_ID_LEN+1] = "";
static double CONTEXT_fontsize = CONTEXT_FONTSIZE;

/* fontname,fontsize to be put next to font labels if needed */
static char CONTEXT_font_explicit[2*MAX_ID_LEN+1] = "";
/* this is only set to >0 if asked for explicitely (for example with set_font(",15")) */
static double CONTEXT_fontsize_explicit = 0.0;

/* the last pointsize used (it will only be changed if it becomes different) */
static double CONTEXT_old_pointsize = 1.0;
/* the last linewidth used (it will only be changed if it becomes different) */
static double CONTEXT_old_linewidth = 1.0;
/* the last linetype used (it will only be changed if it becomes different) */
static int CONTEXT_old_linetype = -3;
/* was the color changed explicitly? */
static TBOOLEAN CONTEXT_color_changed = FALSE;

/* the number of path nodes before a newline (doesn't really matter,
 * could be set to 1000; check if any editors have problems with that) */
#define CONTEXT_LINEMAX 4

/* if we're inside a path (unfinished line) then path_count > 0
 * (PDF has PDF_pathIsOpen) */
static unsigned int CONTEXT_path_count = 0;
/* this true/false switch is used to help distinguish dots from paths */
static unsigned int CONTEXT_path_is_dot = 0;

/* angle of text rotation */
static int CONTEXT_ang = 0;
/* left/middle/right text justification */
static enum JUSTIFY CONTEXT_justify = LEFT;

enum LINEJOIN { LINEJOIN_MITER, LINEJOIN_ROUND, LINEJOIN_BEVEL };
enum LINECAP  { LINECAP_BUTT, LINECAP_ROUND, LINECAP_SQUARE };

/* whether points are drawn with metapost or typeset with TeX (easy configurable) */
enum CONTEXT_POINTS { CONTEXT_POINTS_WITH_METAPOST, CONTEXT_POINTS_WITH_TEX };
/* whether images are inline or written out as PNGs and included (in MKII only external work) */
enum CONTEXT_IMAGES { CONTEXT_IMAGES_INLINE, CONTEXT_IMAGES_EXTERNAL };

/* counts the number of graphics */
static int   CONTEXT_counter = 0;
/* counts the number of external PNG images */
static int   CONTEXT_image_counter = 0;
/* length of basename for storing image name (including path, excluding extension) */
static int   CONTEXT_image_filename_length = 0;
/* if name is a path, remember at which index basename starts */
static int   CONTEXT_image_filename_start = 0;
static char *CONTEXT_image_filename = NULL;
/* whether images will be external or not */
enum CONTEXT_IMAGES CONTEXT_images = CONTEXT_IMAGES_INLINE;

/* Pallete has to be stored for the usage in later plots */
static t_sm_palette *CONTEXT_old_palette;

/*********************/
/* global parameters */
/*********************/

typedef struct CONTEXT_params_t {
	double              xsize;               /* 5in    */
	double              ysize;               /* 3in    */
	size_units          unit;                /* INCHES */
	TBOOLEAN            standalone;          /* false  */
	TBOOLEAN            timestamp;           /* true   */
	char               *header;              /* ""     */
	TBOOLEAN            color;               /* true   */
	TBOOLEAN            dashed;              /* true   */
	enum LINEJOIN       linejoin;            /* MITER  */
	enum LINECAP        linecap;             /* BUTT   */
	double              scale_dashlength;    /* 1.0    */
	double              scale_linewidth;     /* 1.0    */
	double              scale_text;          /* 1.0    */
	enum CONTEXT_POINTS points;              /* CONTEXT_POINTS_WITH_METAPOST */
	enum CONTEXT_IMAGES images;              /* CONTEXT_IMAGES_INLINE */
	char                font[MAX_ID_LEN+1];  /* ""     */
	double              fontsize;            /* 12pt   */
} CONTEXT_params_t;


#define CONTEXT_PARAMS_DEFAULT { \
	CONTEXT_XSIZE_VALUE,\
	CONTEXT_YSIZE_VALUE,\
	INCHES,\
	FALSE,\
	TRUE,\
	NULL,\
	TRUE,\
	TRUE,\
	LINEJOIN_MITER,\
	LINECAP_BUTT,\
	1.0,\
	1.0,\
	1.0,\
	CONTEXT_POINTS_WITH_METAPOST,\
	CONTEXT_IMAGES_INLINE,\
	"",\
	CONTEXT_FONTSIZE\
}

static CONTEXT_params_t CONTEXT_params = CONTEXT_PARAMS_DEFAULT;

enum CONTEXT_id {
	CONTEXT_OPT_DEFAULT,
	CONTEXT_OPT_SIZE,
	CONTEXT_OPT_SIZE_DEFAULT,
	CONTEXT_OPT_INPUT, CONTEXT_OPT_STANDALONE,
	CONTEXT_OPT_TIMESTAMP, CONTEXT_OPT_NOTIMESTAMP,
	CONTEXT_OPT_HEADER, CONTEXT_OPT_NOHEADER,
	CONTEXT_OPT_COLOR, CONTEXT_OPT_MONOCHROME,
	CONTEXT_OPT_DASHED, CONTEXT_OPT_SOLID,
	CONTEXT_OPT_LINEJOIN_MITERED, CONTEXT_OPT_LINEJOIN_ROUNDED, CONTEXT_OPT_LINEJOIN_BEVELED,
	CONTEXT_OPT_LINECAP_BUTT, CONTEXT_OPT_LINECAP_ROUNDED, CONTEXT_OPT_LINECAP_SQUARED,
	CONTEXT_OPT_SCALE_DASHLENGTH, CONTEXT_OPT_SCALE_LINEWIDTH, CONTEXT_OPT_SCALE_TEXT,
	CONTEXT_OPT_POINTS_WITH_METAPOST, CONTEXT_OPT_POINTS_WITH_TEX,
	CONTEXT_OPT_IMAGES_INLINE, CONTEXT_OPT_IMAGES_EXTERNAL,
	CONTEXT_OPT_DEFAULTFONT,
	CONTEXT_OPT_FONT,
	CONTEXT_OPT_OTHER
};
static struct gen_table CONTEXT_opts[] = {
	{ "d$efault", CONTEXT_OPT_DEFAULT },
	{ "size", CONTEXT_OPT_SIZE },
	{ "defaultsize", CONTEXT_OPT_SIZE_DEFAULT },
	{ "inp$ut", CONTEXT_OPT_INPUT },
	{ "stand$alone", CONTEXT_OPT_STANDALONE },
	{ "time$stamp", CONTEXT_OPT_TIMESTAMP },
	{ "notime$stamp", CONTEXT_OPT_NOTIMESTAMP },
	{ "header", CONTEXT_OPT_HEADER },
	{ "noheader", CONTEXT_OPT_NOHEADER },
	{ "col$or", CONTEXT_OPT_COLOR },
	{ "col$our", CONTEXT_OPT_COLOR },
	{ "mono$chrome", CONTEXT_OPT_MONOCHROME },
	{ "da$shed", CONTEXT_OPT_DASHED },
	{ "so$lid", CONTEXT_OPT_SOLID },
	{ "miter$ed", CONTEXT_OPT_LINEJOIN_MITERED },
	{ "rounded", CONTEXT_OPT_LINEJOIN_ROUNDED },
	{ "bevel$ed", CONTEXT_OPT_LINEJOIN_BEVELED },
	{ "butt", CONTEXT_OPT_LINECAP_BUTT },
	{ "round", CONTEXT_OPT_LINECAP_ROUNDED },
	{ "square$d", CONTEXT_OPT_LINECAP_SQUARED },
	{ "dashl$ength", CONTEXT_OPT_SCALE_DASHLENGTH },
	{ "dl", CONTEXT_OPT_SCALE_DASHLENGTH },
	{ "linew$idth", CONTEXT_OPT_SCALE_LINEWIDTH },
	{ "lw", CONTEXT_OPT_SCALE_LINEWIDTH },
	{ "fontscale", CONTEXT_OPT_SCALE_TEXT },
	{ "textscale", CONTEXT_OPT_SCALE_TEXT },                   /* backward compatibility */
	{ "mp$points", CONTEXT_OPT_POINTS_WITH_METAPOST},
	{ "tex$points", CONTEXT_OPT_POINTS_WITH_TEX},
	{ "pointswithmp", CONTEXT_OPT_POINTS_WITH_METAPOST},       /* (removable) backward compatibility */
	{ "pointswithmetapost", CONTEXT_OPT_POINTS_WITH_METAPOST}, /* (removable) backward compatibility */
	{ "pointswithtex", CONTEXT_OPT_POINTS_WITH_TEX},           /* (removable) backward compatibility */
	{ "inline$images", CONTEXT_OPT_IMAGES_INLINE},
	{ "external$images", CONTEXT_OPT_IMAGES_EXTERNAL},
	{ "font", CONTEXT_OPT_FONT },
	{ "defaultfont", CONTEXT_OPT_DEFAULTFONT },
	{ NULL, CONTEXT_OPT_OTHER }
};

/* **********************
 * CONTEXT_params_reset *
 * **********************
 *
 * Resets all parameters of the terminal to their default value.
 */
static void
CONTEXT_params_reset()
{
	static const CONTEXT_params_t CONTEXT_params_default = CONTEXT_PARAMS_DEFAULT;

	/* free the memory with header first */
	if (CONTEXT_params.header) {
		free(CONTEXT_params.header);
		CONTEXT_params.header = NULL;
	}

	memcpy(&CONTEXT_params, &CONTEXT_params_default, sizeof(CONTEXT_params_t));
}


/* *****************
 * CONTEXT_options *
 * *****************
 *
 * Parses "set term context [options]".
 */
TERM_PUBLIC void
CONTEXT_options()
{
	struct value a;
	char   *tmp_string;
	char   tmp_term_options[MAX_LINE_LEN+1] = "";

	while (!END_OF_COMMAND) {
		switch (lookup_table(&CONTEXT_opts[0], c_token)) {
		case CONTEXT_OPT_DEFAULT:
			c_token++;
			/* there should be a better way to do it, but I don't know how */
			CONTEXT_params_reset();
			break;
		case CONTEXT_OPT_SIZE: {
			float xmax_t, ymax_t;
			size_units unit;
			c_token++;

			/* size <xsize> {cm|in}, <ysize> {cm|in} */
			unit = parse_term_size(&xmax_t, &ymax_t, CM);
			CONTEXT_params.xsize = (double)xmax_t / gp_resolution;
			CONTEXT_params.ysize = (double)ymax_t / gp_resolution;
			CONTEXT_params.unit  = unit;
			if (unit == CM) {
				CONTEXT_params.xsize *= 2.54;
				CONTEXT_params.ysize *= 2.54;
			}
			break;
		}
		case CONTEXT_OPT_SIZE_DEFAULT:
			c_token++;
			CONTEXT_params.xsize = CONTEXT_XSIZE_VALUE;
			CONTEXT_params.ysize = CONTEXT_YSIZE_VALUE;
			CONTEXT_params.unit  = CONTEXT_SIZE_UNIT;
			break;
		case CONTEXT_OPT_INPUT:
			c_token++;
			CONTEXT_params.standalone = FALSE;
			break;
		case CONTEXT_OPT_STANDALONE:
			c_token++;
			CONTEXT_params.standalone = TRUE;
			break;
		case CONTEXT_OPT_TIMESTAMP:
			c_token++;
			CONTEXT_params.timestamp = TRUE;
			break;
		case CONTEXT_OPT_NOTIMESTAMP:
			c_token++;
			CONTEXT_params.timestamp = FALSE;
			break;

		case CONTEXT_OPT_HEADER:
			c_token++;
			/* parse the string */
			tmp_string = try_to_get_string();
			if (!tmp_string) {
				int_error(c_token,"String containing header information expected");
			/* only touch the options if the string is OK */
			} else {
				/* remove the old header if any */
				if (CONTEXT_params.header) {
					free(CONTEXT_params.header);
					CONTEXT_params.header = NULL;
				}
				/* and set the new one if nonempty;
				 * empty header will be treated as 'noheader' */
				if (strlen(tmp_string) > 0) {
					CONTEXT_params.header = tmp_string;
				} else {
					free(tmp_string);
				}
			}
			break;
		case CONTEXT_OPT_NOHEADER:
			c_token++;
			/* delete the header if it exists */
			if (CONTEXT_params.header) {
				free(CONTEXT_params.header);
				CONTEXT_params.header = NULL;
			}
			break;
		case CONTEXT_OPT_COLOR:
			c_token++;
			CONTEXT_params.color = TRUE;
			/* just mimick other terminals; no idea what it does;
			   at the moment monochrome is not fully implemented either */
			term->flags &= ~TERM_MONOCHROME;
			break;
		case CONTEXT_OPT_MONOCHROME:
			c_token++;
			CONTEXT_params.color = FALSE;
			term->flags |= TERM_MONOCHROME;
			break;
		case CONTEXT_OPT_DASHED:
			c_token++;
			CONTEXT_params.dashed = TRUE;
			break;
		case CONTEXT_OPT_SOLID:
			c_token++;
			CONTEXT_params.dashed = FALSE;
			break;
		case CONTEXT_OPT_LINEJOIN_MITERED:
			c_token++;
			CONTEXT_params.linejoin = LINEJOIN_MITER;
			break;
		case CONTEXT_OPT_LINEJOIN_ROUNDED:
			c_token++;
			CONTEXT_params.linejoin = LINEJOIN_ROUND;
			break;
		case CONTEXT_OPT_LINEJOIN_BEVELED:
			c_token++;
			CONTEXT_params.linejoin = LINEJOIN_BEVEL;
			break;
		case CONTEXT_OPT_LINECAP_BUTT:
			c_token++;
			CONTEXT_params.linecap = LINECAP_BUTT;
			break;
		case CONTEXT_OPT_LINECAP_ROUNDED:
			c_token++;
			CONTEXT_params.linecap = LINECAP_ROUND;
			break;
		case CONTEXT_OPT_LINECAP_SQUARED:
			c_token++;
			CONTEXT_params.linecap = LINECAP_SQUARE;
			break;
		case CONTEXT_OPT_SCALE_DASHLENGTH:
			c_token++;
			CONTEXT_params.scale_dashlength = real(const_express(&a));
			break;
		case CONTEXT_OPT_SCALE_LINEWIDTH:
			c_token++;
			CONTEXT_params.scale_linewidth = real(const_express(&a));
			break;
		case CONTEXT_OPT_SCALE_TEXT:
			c_token++;
			CONTEXT_params.scale_text = real(const_express(&a));
			break;
		case CONTEXT_OPT_DEFAULTFONT:
			c_token++;
			/* CONTEXT_params.font should be an empty string */
			CONTEXT_params.font[0] = 0;
			/* default fontsize is 12pt */
			CONTEXT_params.fontsize = CONTEXT_FONTSIZE;
			break;
		case CONTEXT_OPT_POINTS_WITH_METAPOST:
			c_token++;
			CONTEXT_params.points = CONTEXT_POINTS_WITH_METAPOST;
			break;
		case CONTEXT_OPT_POINTS_WITH_TEX:
			c_token++;
			CONTEXT_params.points = CONTEXT_POINTS_WITH_TEX;
			break;
		case CONTEXT_OPT_IMAGES_INLINE:
			c_token++;
			CONTEXT_params.images = CONTEXT_IMAGES_INLINE;
			break;
		case CONTEXT_OPT_IMAGES_EXTERNAL:
#ifdef WRITE_PNG_IMAGE
			c_token++;
			CONTEXT_params.images = CONTEXT_IMAGES_EXTERNAL;
#else
			int_warn(c_token, "Gnuplot was built without support for PNG images. You cannot use this option unless you rebuild gnuplot.");
#endif
			break;
		/*
		 * The preferred way to set the font is to set it in a document itself,
		 * labels in gnuplot in graphs will then inherit that font.
		 *
		 * However, it is important to tell gnuplot which size is going to be used,
		 * so that it can estimate size of text labels.
		 *
		 * Whenever you specify
		 *     set term context font "fontname,14"
		 *
		 * there are two possibilities:
		 * - if STANDALONE mode is on, then the whole string will be used as
		 *   \setupbodyfont[fontname,14pt]
		 *   somewhere on top of the document (you still have to make sure that you
		 *   included the proper typescript, so that "fontname" will be recognised
		 * - in the other case (INPUT mode) only the font size will be used
		 *   internally to estimate sizes of labels, but the font name
		 *   won't be written anywhere
		 */
		case CONTEXT_OPT_FONT: {
			double tmp_fontsize;
			char tmp_font[MAX_ID_LEN+1] = "";
			c_token++;
			if ((tmp_string = try_to_get_string()) && (tmp_string != NULL)) {
				CONTEXT_fontstring_parse(tmp_string, tmp_font, MAX_ID_LEN+1, &tmp_fontsize);
				/* copies font name to parameters */
				strncpy(CONTEXT_params.font, tmp_font, sizeof(CONTEXT_params.font));
				tmp_font[MAX_ID_LEN] = NUL;
				free(tmp_string);
				/* save font size:
				 *
				 * - if size > 0, copy
				 * - if size < 0, fix the size to default value (12pt)
				 * - if size = 0, ignore
				 */
				if (tmp_fontsize > 0)
					CONTEXT_params.fontsize = tmp_fontsize;
				else if (tmp_fontsize < 0)
					CONTEXT_params.fontsize = CONTEXT_FONTSIZE;
			}
			break;
		}
		case CONTEXT_OPT_OTHER:
		default:
			/* error */
			int_error(c_token, "extraneous argument in set terminal %s",term->name);
			break;
		}
	}

	/* current font size in pt (to be used in CONTEXT_adjust_dimensions) */
	CONTEXT_fontsize = CONTEXT_params.fontsize;

	/* sets term->xmax, ymax, vchar, hchar */
	CONTEXT_adjust_dimensions();

	snprintf(term_options, sizeof(term_options),
			"size %g%s,%g%s %s %s %s",
			CONTEXT_params.xsize,
			(CONTEXT_params.unit == INCHES) ? "in" : "cm",
			CONTEXT_params.ysize,
			(CONTEXT_params.unit == INCHES) ? "in" : "cm",
			CONTEXT_params.standalone ? "standalone" : "input",
			CONTEXT_params.timestamp ? "timestamp" : "notimestamp",
			CONTEXT_params.header == NULL ? "noheader \\\n   " : "\\\n   header ");

	if (CONTEXT_params.header != NULL) {
		strncat(term_options,"\"",                  sizeof(term_options)-strlen(term_options)-1);
		strncat(term_options,CONTEXT_params.header, sizeof(term_options)-strlen(term_options)-1);
		strncat(term_options,"\" \\\n   ",          sizeof(term_options)-strlen(term_options)-1);
	}

	strncat(term_options,
		CONTEXT_params.color ? "color " : "monochrome ",
		sizeof(term_options)-strlen(term_options)-1);

	switch (CONTEXT_params.linejoin) {
		case LINEJOIN_MITER:
			strncat(term_options, "mitered ",
				sizeof(term_options)-strlen(term_options)-1);
                        break;
		case LINEJOIN_ROUND:
			strncat(term_options, "rounded ",
				sizeof(term_options)-strlen(term_options)-1);
                        break;
		case LINEJOIN_BEVEL:
			strncat(term_options, "beveled ",
				sizeof(term_options)-strlen(term_options)-1);
                        break;
	}
	switch (CONTEXT_params.linecap) {
		case LINECAP_BUTT  :
			strncat(term_options, "butt",
				sizeof(term_options)-strlen(term_options)-1);
                        break;
		case LINECAP_ROUND :
			strncat(term_options, "round",
				sizeof(term_options)-strlen(term_options)-1);
                        break;
		case LINECAP_SQUARE:
			strncat(term_options, "squared",
				sizeof(term_options)-strlen(term_options)-1);
                        break;
	}

	snprintf(tmp_term_options, sizeof(tmp_term_options),
		" %s dashlength %g linewidth %g fontscale %g \\\n   ",
		CONTEXT_params.dashed ? "dashed" : "solid",
		CONTEXT_params.scale_dashlength,
		CONTEXT_params.scale_linewidth,
		CONTEXT_params.scale_text
		);
	strncat(term_options, tmp_term_options, sizeof(term_options)-strlen(term_options)-1);

	switch (CONTEXT_params.points) {
		case CONTEXT_POINTS_WITH_TEX :
			strncat(term_options, "texpoints ",
				sizeof(term_options)-strlen(term_options)-1);
                        break;
		case CONTEXT_POINTS_WITH_METAPOST :
			strncat(term_options, "mppoints ",
				sizeof(term_options)-strlen(term_options)-1);
                        break;
	}
#ifdef WRITE_PNG_IMAGE
	switch (CONTEXT_params.images) {
		case CONTEXT_IMAGES_INLINE :
			strncat(term_options, "inlineimages ",
				sizeof(term_options)-strlen(term_options)-1);
                        break;
		case CONTEXT_IMAGES_EXTERNAL :
			strncat(term_options, "externalimages ",
				sizeof(term_options)-strlen(term_options)-1);
                        break;
	}
#endif
	snprintf(tmp_term_options, sizeof(tmp_term_options), "font \"%s,%g\"",
		CONTEXT_params.font, CONTEXT_params.fontsize);
	strncat(term_options, tmp_term_options, sizeof(term_options) - strlen(term_options)-1);
}

/* **************
 * CONTEXT_init *
 * **************
 *
 * Starts a new file.
 *
 * XXX: "set term context" multiple times will only include those graphics
 *      that were create before issuing a new "set term context options"
 *      this should be fixed in the core by reopening the file
 *      (removing previously written content).
 * - PDF & binary terminals start a new file
 * - PS & TeX-based terminals continue
 */
TERM_PUBLIC void
CONTEXT_init()
{
	time_t now;
	char timebuffer[100];
	int i;

	time(&now);

	CONTEXT_posx = CONTEXT_posy = 0;
	CONTEXT_path_count = 0;
	CONTEXT_path_is_dot = 0;

	CONTEXT_counter = 0;

	/* setup bitmap images */
	CONTEXT_image_counter = 0;
	/* the default is to use inline images */
	CONTEXT_images = CONTEXT_IMAGES_INLINE;
	
	/* only if external images are both requested and supported, we switch to them (double paranoia) */
	/* delete the stored filename first */
	if (CONTEXT_image_filename) {
		free(CONTEXT_image_filename);
		CONTEXT_image_filename = NULL;
		CONTEXT_image_filename_length = 0;
		CONTEXT_image_filename_start  = 0;
	};
#ifdef WRITE_PNG_IMAGE
	if (CONTEXT_params.images == CONTEXT_IMAGES_EXTERNAL) {
		CONTEXT_images = CONTEXT_IMAGES_EXTERNAL;

		/* but only if 'set output' was set because we use that string as base for image names */
		if (outstr) {
			CONTEXT_image_filename_length = strlen(outstr);
			CONTEXT_image_filename_start  = strlen(outstr) - strlen(gp_basename(outstr));
			/* we will cut off the last .tex ending if present */
			/* find the last dot if present */
			for (i = CONTEXT_image_filename_length - 1; i >= 0 && outstr[i] != '.'; i--);
			if (outstr[i] == '.')
				CONTEXT_image_filename_length = i;
			/* it would also be very nice to do some sanity checks on filenames */

			/* <name>.xx.png; must be at least 7 characters long */
			CONTEXT_image_filename = (char *)gp_alloc(CONTEXT_image_filename_length + 10, "ConTeXt image filename");
			strncpy(CONTEXT_image_filename, outstr, CONTEXT_image_filename_length);
			CONTEXT_image_filename[CONTEXT_image_filename_length] = 0;
		} else {
			CONTEXT_image_filename_length = strlen("gp_image");
			CONTEXT_image_filename_start  = 0;
			/* <name>.xx.png; must be at least 7 characters long */
			CONTEXT_image_filename = (char *)gp_alloc(CONTEXT_image_filename_length + 10, "ConTeXt image filename");
			strncpy(CONTEXT_image_filename, "gp_image", CONTEXT_image_filename_length);
			CONTEXT_image_filename[CONTEXT_image_filename_length] = 0;
		}
	}
#endif

	fprintf(gpoutfile, "%% Written by ConTeXt terminal for GNUPLOT");
	if (CONTEXT_params.timestamp) {
		if (strftime(timebuffer, 100, "%Y-%m-%d %H:%M %Z", localtime(&now)) != 0)
			fprintf(gpoutfile, " on: %s", timebuffer);
	}
	fprintf(gpoutfile, "\n");
	fprintf(gpoutfile, "%% GNUPLOT version: %s.%s, terminal version: %s.%s (%s)\n",
		gnuplot_version, gnuplot_patchlevel, CONTEXT_term_version, CONTEXT_term_patch, CONTEXT_term_date);
	fprintf(gpoutfile, "%% See also http://wiki.contextgarden.net/Gnuplot\n%%\n");

	/* place the header first if this is a standalone graphic */
	if (CONTEXT_params.standalone) {
		/* If encoding is explicitely set to UTF-8 by gnuplot, use that setting.
		 * \enableregime only makes a difference for pdfTeX; in LuaTeX and XeTeX UTF-8 is already default,
		 * so this line will be ignored.
		 *
		 * There is no extra support for other encodings on purpose:
		 * - ConTeXt doesn't support all encodings supported by Gnuplot.
		 * - In LuaTeX and XeTeX one should not use any other encoding anyway.
		 * - pdfTeX users are free to use "header '\enableregime[...]'" */
		switch (encoding) {
			case S_ENC_UTF8:
				fputs("\\enableregime\n   [utf-8]\n", gpoutfile);
				break;
			default:
				/* do nothing */
				break;
		}
		/* load the gnuplot module */
		fputs("\\usemodule\n   [gnuplot]\n", gpoutfile);
		/* enable or disable color (the only place where "color" is indeed used so far) */
		fprintf(gpoutfile, "\\setupcolors\n   [state=%s]\n", CONTEXT_params.color ? "start" : "stop");
		/* additional user-provided header information (if available) */
		if (CONTEXT_params.header)
			fprintf(gpoutfile, "%s\n", CONTEXT_params.header);
		/* for some reason setting \bodyfontenvironment is needed,
		 * otherwise \switchtobodyfont[name] doesn't work OK */
		if (!(CONTEXT_params.fontsize == CONTEXT_FONTSIZE))
			fprintf(gpoutfile, "\\definebodyfontenvironment\n   [%gpt]\n",
				CONTEXT_params.fontsize);
		/* set the proper font: \setupbodyfont[{fontname,}fontsize sizeunit] */
		fprintf(gpoutfile, "\\setupbodyfont\n   [%s%s%gpt]\n",
			CONTEXT_params.font,
			/* write a comma only if the last string was non-empty */
			((strlen(CONTEXT_params.font)>0) ? "," : ""),
			CONTEXT_params.fontsize);

		/*---------*
		 * options *
		 *---------*/
		fprintf(gpoutfile, "\\setupGNUPLOTterminal\n   [context]\n   [");
		
		/* color (gp_use_color): yes/no (true/false)
		 * default: yes
		 * - doesn't do anything useful yet;
		 *   and besides that, it's already set in \setupcolors[state=start] */
		/* fprintf(gpoutfile, "    color=%s, %% *yes* | no\n", CONTEXT_params.color ? "yes" : "no"); */
		
		/* linejoin: mitered/rounded/beveled
		 * default: mitered */
		fprintf(gpoutfile, "linejoin=");
		switch (CONTEXT_params.linejoin) {
			case LINEJOIN_MITER: fprintf(gpoutfile, "mitered"); break;
			case LINEJOIN_ROUND: fprintf(gpoutfile, "rounded"); break;
			case LINEJOIN_BEVEL: fprintf(gpoutfile, "beveled"); break;
		}
		fprintf(gpoutfile, ", %% *mitered* | rounded | beveled\n");
		
		/* linecap: butt/rounded/squared
		 * default: butt */
		fprintf(gpoutfile, "    linecap=");
		switch (CONTEXT_params.linecap) {
			case LINECAP_BUTT  : fprintf(gpoutfile, "butt"); break;
			case LINECAP_ROUND : fprintf(gpoutfile, "rounded"); break;
			case LINECAP_SQUARE: fprintf(gpoutfile, "squared"); break;
		}
		fprintf(gpoutfile, ", %% *butt* | rounded | squared\n");
		
		/* dashed (gp_use_dashed): yes/no (true/false)
		 * default: yes */
		fprintf(gpoutfile, "    dashed=%s, %% *yes* | no\n", CONTEXT_params.dashed ? "yes" : "no");
		/* dashlength (gp_scale_dashlength): 1.0 */
		fprintf(gpoutfile, "    dashlength=%g, %% scaling factor for dash lengths\n", CONTEXT_params.scale_dashlength);
		
		/* linewidth (gp_scale_linewidth): 1.0 */
		fprintf(gpoutfile, "    linewidth=%g, %% scaling factor for line widths (1.0 means 0.5bp)\n", CONTEXT_params.scale_linewidth);

		/* fontscale (gp_scale_text): 1.0 */
		/* written out just for reference - it's commented out since it needs to be part of graphic
		   and affects estimation of label sizes */
		fprintf(gpoutfile, "    %%fontscale=%g, %% scaling factor for text labels\n", CONTEXT_params.scale_text);
		
		/* points (gp_points_with): metapost/tex (gp_points_with_metapost/gp_points_with_tex)
		 * default: metapost */
		fprintf(gpoutfile, "    points=%s, %% *metapost* | tex (Should points be drawn with MetaPost or TeX?)\n",
			CONTEXT_params.points == CONTEXT_POINTS_WITH_METAPOST ? "metapost" : "tex");

		/* images
		 * default: inline */
		fprintf(gpoutfile, "    images=%s] %% *inline* | external (inline only works in MKIV, external requires png support in gnuplot)\n",
			CONTEXT_images == CONTEXT_IMAGES_INLINE ? "inline" : "external");

		/*----------------*
		 * end of options *
		 *----------------*/

		fputs("\n\\starttext\n\n", gpoutfile);
	} else {
		/* Sorry, nothing! In non-standalone graphic, parameters make no sense.
		 * Setup everything in the file which includes such a graphic instead.
		 */
	}
}

/* ***************
 * CONTEXT_reset *
 * ***************
 *
 * finish writing the file
 */
TERM_PUBLIC void
CONTEXT_reset()
{
	/* we only have to end the document if this is a stand-alone graphic */
	if (CONTEXT_params.standalone) {
		fputs("\\stoptext\n", gpoutfile);
	} else {
		/* This means that any subsequent plots to the same file will be ignored.
		 * I don't like that - gnuplot should delete the old contents instead,
		 * just as it does in case of PNG or PDF -
		 * but it will be at least consistent with standalone graphics that way
		 */
		fputs("\\endinput\n", gpoutfile);
	}
	/* deallocate image name if present */
	if (CONTEXT_image_filename) {
		free(CONTEXT_image_filename);
		CONTEXT_image_filename = NULL;
		CONTEXT_image_filename_length = 0;
		CONTEXT_image_filename_start  = 0;
	};
}

/* **************
 * CONTEXT_text *
 * **************
 *
 * Ends the current graphic.
 */
TERM_PUBLIC void
CONTEXT_text()
{
	/* close and draw the current path first */
	if (CONTEXT_path_count > 0)
		CONTEXT_endpath();

	fprintf(gpoutfile, "setbounds currentpicture to unitsquare xyscaled (w,h);\n");

	/* standalone graphic is a whole-page graphic */
	if (CONTEXT_params.standalone) {
		fputs("\\stopGNUPLOTpage\n", gpoutfile);
	/* otherwise we define a MPgraphic to be included later */
	} else {
		fputs("\\stopGNUPLOTgraphic\n", gpoutfile);
	}
}

/* ******************
 * CONTEXT_graphics *
 * ******************
 *
 * Starts a new graphic.
 */
TERM_PUBLIC void
CONTEXT_graphics()
{
	/* standalone graphic is a whole-page graphic */
	if (CONTEXT_params.standalone) {
		fprintf(gpoutfile, "\\startGNUPLOTpage %% Graphic Nr. %d\n", ++CONTEXT_counter);
	/* otherwise we define a MPgraphic to be included later */
	} else {
		/* the first parameter holds the graphic number */
		fprintf(gpoutfile, "\\startGNUPLOTgraphic[%d]\n", ++CONTEXT_counter);
	}

	fprintf(gpoutfile, "string gnuplotversion; gnuplotversion := \"%s\";\n", gnuplot_version);
	fprintf(gpoutfile, "string termversion;    termversion    := \"%s\";\n", CONTEXT_term_version);
	/*
	 * MetaPost can only handle numbers up to 4096. Too high resolution
	 * would thus result in number overflow, that's why we scale down all the
	 * integers from gnuplot by 1000 and multiply those numbers later by
	 * appropriate scaling factor 'a' to get the proper dimensions.
	 */
	fprintf(gpoutfile, "%% scaling factor, width and height of the figure\na := 1cm; w := %.3fa; h := %.3fa; %% (%g%s, %g%s)\n",
		CONTEXT_params.xsize * ((CONTEXT_params.unit == INCHES) ? 2.54 : 1), /* cm */
		CONTEXT_params.ysize * ((CONTEXT_params.unit == INCHES) ? 2.54 : 1), /* cm */
		CONTEXT_params.xsize, (CONTEXT_params.unit == INCHES) ? "in" : "cm",
		CONTEXT_params.ysize, (CONTEXT_params.unit == INCHES) ? "in" : "cm");
	/* TODO: the following if-else could be slightly nicer */
	if (CONTEXT_images == CONTEXT_IMAGES_INLINE) {
		fprintf(gpoutfile, "%% temporary variable for storing the path and images\nsave p, img, ima; path p; string img, ima;\n");
	} else {
		fprintf(gpoutfile, "%% temporary variable for storing the path\nsave p; path p;\n");
	}
	fprintf(gpoutfile, "%% -------------------------\n");
	fprintf(gpoutfile, "%% Different initialisations\n");
	fprintf(gpoutfile, "%% -------------------------\n");
	fprintf(gpoutfile, "%% for additional user-defined settings\ngp_setup_before;\n");
	/* needed (depends on terminal settings & needs to be passed) */
	fprintf(gpoutfile, "%% text scaling factor for the whole figure\n");
	fprintf(gpoutfile, "gp_scale_text := %g;\n", CONTEXT_params.scale_text);
	fprintf(gpoutfile, "%% pointsize scaling factor\n");
	fprintf(gpoutfile, "gp_set_pointsize(%g);\n", CONTEXT_old_pointsize);
	/* needed (provided by terminal) */
	fprintf(gpoutfile, "%% linewidth scaling factor for individual lines\n");
	fprintf(gpoutfile, "gp_set_linewidth(%g);\n", CONTEXT_old_linewidth);
	fprintf(gpoutfile, "%% for additional user-defined settings\ngp_setup_after;\n");
	fprintf(gpoutfile, "%% -------------------------\n");

	/* since palette is initialized only once, subsequent plots wouldn't see it
	 * unless we write it on the top of relevant plots explicitely */
	if (is_plot_with_palette()) {
		CONTEXT_write_palette(CONTEXT_old_palette);
	}
	
	/* needed, otherwise the first linetype(-2) would be ignored */
	CONTEXT_old_linetype = -3;
	/* different initializations - not really needed, but they cannot hurt */
	CONTEXT_posx = CONTEXT_posy = 0;
	CONTEXT_path_count = 0;
	CONTEXT_path_is_dot = 0;
}

/* ---------------
 * CONTEXT_endpath
 * ---------------
 *
 * Closes and strokes (draws) the current path.
 *
 * It the path ends where it started, it ends it with --cycle (we get cyclic path),
 * otherwise just with a semicolon.
 */
static void
CONTEXT_endpath()
{
	/* if we have a dot, draw only the dot */
	if (CONTEXT_path_is_dot) {
		fprintf(gpoutfile, "gp_dot(%.3fa,%.3fa);\n", 0.001*CONTEXT_posx, 0.001*CONTEXT_posy);
		CONTEXT_path_is_dot = 0;
	
	/* cyclic path, so let's end it with "--cycle" */
	} else if ((CONTEXT_posx == CONTEXT_path_start_x) && (CONTEXT_posy == CONTEXT_path_start_y)) {
		fputs("--cycle;\ngp_draw(p);\n", gpoutfile);
	
	/* regular non-cyclic path */
	} else {
		fprintf(gpoutfile, "--(%.3fa,%.3fa);\ngp_draw(p);\n", 0.001*CONTEXT_posx, 0.001*CONTEXT_posy);
	}

	/* we're not inside path any more */
	CONTEXT_path_count = 0;
}

/* **************
 * CONTEXT_move *
 * **************
 *
 * Remembers the new location for a path.
 *
 * If it doesn't differ from the current location, this is simply ignored.
 * If we're still in the middle of path construction and location differs,
 * it strokes the old path.
 *
 */
TERM_PUBLIC void
CONTEXT_move(unsigned int x, unsigned int y)
{
	/* we seem to be there already */
	if ((x == CONTEXT_posx) && (y == CONTEXT_posy))
		return;

	/* close and draw the current path before the move */
	if (CONTEXT_path_count > 0)
		CONTEXT_endpath();

	CONTEXT_posx = x;
	CONTEXT_posy = y;
}

/* -----------------
 * CONTEXT_startpath
 * -----------------
 *
 * Starts ([but not yet] drawing) a new path.
 */
static void
CONTEXT_startpath()
{
	CONTEXT_path_start_x = CONTEXT_posx;
	CONTEXT_path_start_y = CONTEXT_posy;
	CONTEXT_path_count = 2;

	fprintf(gpoutfile, "p := (%.3fa,%.3fa)", 0.001*CONTEXT_posx, 0.001*CONTEXT_posy);
}

/* ****************
 * CONTEXT_vector *
 * ****************
 *
 * Prolongs the current path for an additional line (from the last point to (x,y))
 * unless it has a zero-length.
 *
 * Points have to be treated as a special case, since gnuplot sometimes tries
 * to draw them as moveto(a,b)--lineto(a,b) - without the proper linecap,
 * that wouldn't draw anything in MetaPost or PS.
 * (I hope that I got that part right, but I'm not completely sure.)
 */
TERM_PUBLIC void
CONTEXT_vector(unsigned int x, unsigned int y)
{
	/* this is zero-length line (or a dot)
	 *
	 * stupid background, has to handle
	 * - move(0,0), vector(0,0), whatever: draw a dot
	 * - move(0,0), vector(0,0), vector (1,1): draw a line
	 */
	if ((x == CONTEXT_posx) && (y==CONTEXT_posy)) {
		/* as long as this is still a dot candidate, mark it so
		 * however - further vector() commands may set this back to 0 */
		if (CONTEXT_path_count == 0)
			CONTEXT_path_is_dot = 1;
		/* if some path was already drawn up to this place, ignore (it's not a dot) */
		return;
	}

	/* start the path if none is started yet */
	if (CONTEXT_path_count == 0) {
		/* the path is not a dot */
		CONTEXT_path_is_dot = 0;
		CONTEXT_startpath();
	} else {
		/* or prevent too long lines if you're in the middle of a path */
		if ((CONTEXT_path_count % CONTEXT_LINEMAX) == 2) {
			fputs("\n  ", gpoutfile);
			CONTEXT_path_count = 2;
		}
		/* and output the previous point */
		fprintf(gpoutfile, "--(%.3fa,%.3fa)", 0.001*CONTEXT_posx, 0.001*CONTEXT_posy);
	}

	CONTEXT_posx = x;
	CONTEXT_posy = y;
	CONTEXT_path_count++;
}

/* ******************
 * CONTEXT_linetype *
 * ******************
 *
 * - If only color has been changed (recently), but not the linetype,
 *   it resets only the color.
 * - If linetype was changed, it sets the new linetype
 */
TERM_PUBLIC void
CONTEXT_linetype(int lt)
{
	/* reset the color in case it has been changed in CONTEXT_set_color() */
	if (CONTEXT_old_linetype != lt || CONTEXT_color_changed) {
		/* close and draw the current path first */
		if (CONTEXT_path_count > 0)
			CONTEXT_endpath();

		fprintf(gpoutfile, "gp_set_linetype(%d);\n", lt);

		CONTEXT_old_linetype = lt;
		CONTEXT_color_changed = FALSE;
	}
}

/* ******************
 * CONTEXT_put_text *
 * ******************
 *
 * Places text labels.
 */
TERM_PUBLIC void
CONTEXT_put_text(unsigned int x, unsigned int y, const char str[])
{
	const char *s; /* pointer to string */
	int  alignment = 0;
	char alignments[3][10] = {"center", "left", "right"};

	/* ignore empty strings */
	if (!str || !strlen(str))
		return;

	/* close and draw the current path first */
	if (CONTEXT_path_count > 0)
		CONTEXT_endpath();

	/* see the values of "alignments" above */
	switch (CONTEXT_justify) {
		case CENTRE:
			alignment = 0;
			break;
		case LEFT:
			alignment = 1;
			break;
		case RIGHT:
			alignment = 2;
			break;
	}

	/* remove whitespaces at the beginning of string
	 * (usually problem in positive numbers)
	 * They interfere with positioning: whitespace at the beginning takes
	 * some place although it's invisible, so left-aligned and centered labels
	 * are posioned wrong otherwise.
	 * Example:
	 *   -1 0 1 2: centered labels on x axis
	 * if we had a space in front, positive numbers would be "centered" in a weird way*/
	for (s = str; s[0] == ' '; s++);

	/* label position */
	fprintf(gpoutfile, "gp_put_text((%.3fa, %.3fa), ", 0.001*x, 0.001*y);
	/* angle of rotation - optional and needed only if it's different from 0 */
	if (CONTEXT_ang != 0)
		fprintf(gpoutfile, "angle(%d), ", CONTEXT_ang);

	/* alignment - "center" is optional, but we'll add it anyway */
	fprintf(gpoutfile, "align(%s), \\sometxt[gp]", alignments[alignment]);
	/* fontface/fontsize - optional second argument */
	if (CONTEXT_font_explicit[0] != 0)
		fprintf(gpoutfile, "[%s]", CONTEXT_font_explicit);
	/* finally the text label itself */
	fprintf(gpoutfile, "{%s});\n", s);
}


/* ********************
 * CONTEXT_text_angle *
 * ********************
 *
 * Saves text angle to be used for text labels.
 */
TERM_PUBLIC int
CONTEXT_text_angle(int ang)
{
	CONTEXT_ang = ang;
	return TRUE;
}

/* **********************
 * CONTEXT_justify_text *
 * **********************
 *
 * Saves horizontal text justification (left/middle/right) to be used for text labels.
 */
TERM_PUBLIC int
CONTEXT_justify_text(enum JUSTIFY mode)
{
	CONTEXT_justify = mode;
	return TRUE;
}

/* ***************
 * CONTEXT_point *
 * ***************
 *
 * There are two/three possible ways of drawing points in ConTeXt:
 * - let gnuplot draw the points with standard move/vector commands
 *   (points_default): not enabled
 * - use the points predefined in mp-gnuplot.mp (drawn with metapost)
 *   which can easily be redefined
 *   (points_with_metapost)
 * - use symbols from a symbol set predefined in m-gnuplot.tex (drawn with TeX)
 *   (points_with_tex)
 *
 * At first this routine took care of that, but now it's up to the high-level
 * user interface to switch between the last two options.
 */
TERM_PUBLIC void
CONTEXT_point (unsigned int x, unsigned int y, int number)
{
	/* finish the current line first before the move */
	if (CONTEXT_path_count > 0)
		CONTEXT_endpath();

	fprintf(gpoutfile, "gp_point(%.3fa,%.3fa,%d);\n", 0.001*x, 0.001*y, number);
}

/* ***************
 * CONTEXT_arrow *
 * ***************
 * ConTeXt could draw nice arrows on its own and in such a way that user could
 * simply redefine arrow heads in the template file.
 *
 * This function is left here just in case that anyoune would find it useful
 * to define his own arrow-drawing commands.
 *
 * Currently it just calls the default gnuplot function for drawing arrows.
 */
TERM_PUBLIC void
CONTEXT_arrow (unsigned int sx, unsigned int sy, unsigned int ex, unsigned int ey, int head)
{
	do_arrow(sx, sy, ex, ey, head);
}


/* ------------------------
 * CONTEXT_fontstring_parse 
 * ------------------------
 *
 * Parses from_string, which is divided by commas (,)
 * and copies the whole content to to_string except for the part
 * which starts with a numeric value.
 *
 * That value is interpreted separately and saved to fontsize.
 *
 * to_size is the size of to_string which may not be exceeded while copying the string
 */
static void
CONTEXT_fontstring_parse(char *from_string, char *to_string, int to_size, double *fontsize)
{
	double tmp_fontsize = 0.;
	char * comma;
	size_t n;

	comma = strrchr(from_string, ',');
	if (comma) {
		sscanf(comma + 1, "%lf", &tmp_fontsize);
		n = comma - from_string;
	} else {
		n = strlen(from_string);
	}
	*fontsize = tmp_fontsize;
	if (n >= to_size)
		n = to_size - 1;
	memcpy(to_string, from_string, n);
	to_string[n] = NUL;
}


/* -------------------------
 * CONTEXT_adjust_dimensions
 * -------------------------
 *
 * - sets the v_char and h_char based on current font size (approximation only)
 *   using CONTEXT_fontsize in points (from CONTEXT_params.fontsize) and CONTEXT_params.scale_text
 * - sets xmax and ymax based on CONTEXT_params.xsize and CONTEXT_params.ysize
 */
static void
CONTEXT_adjust_dimensions()
{
	/* sets vertical dimension of characters based on current fontsize in pt */
	term->v_char = (unsigned int)((double)CONTEXT_DPI *
		CONTEXT_fontsize / 72.27 * CONTEXT_params.scale_text + 0.5);
	/* based on proportions of LM digits at 12pt */
	term->h_char = (unsigned int)(CONTEXT_LM_H_TO_V_RATIO * term->v_char + 0.5);

	/* we might want to fix CONTEXT_DPI in case that the figure becomes too big */
	if (CONTEXT_params.unit == INCHES) {
		term->xmax = (unsigned int)((double)CONTEXT_DPI  * CONTEXT_params.xsize + 0.5);
		term->ymax = (unsigned int)((double)CONTEXT_DPI  * CONTEXT_params.ysize + 0.5);
	} else {
		term->xmax = (unsigned int)((double)CONTEXT_DPCM * CONTEXT_params.xsize + 0.5);
		term->ymax = (unsigned int)((double)CONTEXT_DPCM * CONTEXT_params.ysize + 0.5);
	}
}

/* *****************
 * CONTEXT_set_font*
 * *****************
 *
 * Official description:
 * - empty string restores the terminal's default font
 * - fonts are selected as strings "name,size",
 *   where size should be a floating point number interpreted as "pt" (point)
 *
 * It's the user's own responsibility to make sure that the proper typescripts
 * are included in the header, else the selected font won't work out-of-the-box
 *
 * The ConTeXt terminal should support things such as
 *   "iwona,ss,12"   (iwona sans serif) or
 *   ",10"           (10 points)  or
 *   "tt"            (typewriter)
 *
 * The routine saves font name to CONTEXT_font
 * and fontsize to CONTEXT_fontsize.
 *
 * The two are joined in CONTEXT_font_explicit for the usage in
 *   \sometxt[gp][fontname,fontsize]{label}
 */
TERM_PUBLIC int
CONTEXT_set_font(const char *font)
{
	char tmp_fontstring[MAX_ID_LEN+1] = "";

	/* saves font name & family to CONTEXT_font */
	CONTEXT_fontstring_parse((char *)font, CONTEXT_font, sizeof(CONTEXT_font), &CONTEXT_fontsize_explicit);
	strncpy(CONTEXT_font_explicit, CONTEXT_font, sizeof(CONTEXT_font_explicit));

	/* valid fontsize has been provided */
	if (CONTEXT_fontsize_explicit > 0.) { /* XXX: if valid */

		CONTEXT_fontsize = CONTEXT_fontsize_explicit;

		snprintf(tmp_fontstring, sizeof(tmp_fontstring), ",%gpt", CONTEXT_fontsize_explicit);
		strncat(CONTEXT_font_explicit, tmp_fontstring, 
                        sizeof(CONTEXT_font_explicit) - strlen(CONTEXT_font_explicit)-1);
		tmp_fontstring[MAX_ID_LEN] = NUL;

	/* no fontsize has been provided: switch back to default terminal fontsize */
	} else if (CONTEXT_fontsize_explicit == 0) {
		CONTEXT_fontsize = CONTEXT_params.fontsize;
	}

	/* tell to gnuplot how big the fonts in labels are */
	CONTEXT_adjust_dimensions();

	return TRUE;
}

/* *******************
 * CONTEXT_pointsize *
 * *******************
 *
 * Sets the (relative) point size for subsequent points
 *
 * The base point size is defined "somewhere else":
 * - depends on the font[size] used when "texpoints" option is on
 */
TERM_PUBLIC void
CONTEXT_pointsize(double pointsize)
{
	/*
	 * my first thought was not to allow negative sizes of points,
	 * but I see no reason why one shouldn't be able to play with
	 * inverted point shapes, so finally I commented this out again
	 *
	 *   if (pointsize < 0)
	 *      pointsize = 1;
	 */
	
	if (CONTEXT_old_pointsize != pointsize) {
		/* close and draw the current path first */
		if (CONTEXT_path_count > 0)
			CONTEXT_endpath();
		fprintf(gpoutfile, "gp_set_pointsize(%.3f);\n", pointsize);
		CONTEXT_old_pointsize = pointsize;
	}
}

/* *****************
 * CONTEXT_fillbox *
 * *****************
 *
 * Creates the path for the rectangle and calls the CONTEXT_fill(style)
 * routine (shared with CONTEXT_filled_polygon) to actually fill that shape
 */
TERM_PUBLIC void
CONTEXT_fillbox(int style, unsigned int x1, unsigned int y1, unsigned int width, unsigned int height)
{
	/* close and draw the current path first */
	if (CONTEXT_path_count > 0)
		CONTEXT_endpath();

	/* create a new path */
	fprintf(gpoutfile, "p := unitsquare xyscaled (%.3fa,%.3fa) shifted (%.3fa,%.3fa);\n", 0.001*width, 0.001*height, 0.001*x1, 0.001*y1);
	/* fprintf(gpoutfile, "p := gp_rect ((%.3fa,%.3fa),(%.3fa,%.3fa));\n", 0.001*x1, 0.001*y1, 0.001*width, 0.001*height); */
	
	/* fills the box according to the "style"
	 * the code went out of this routine because of undocumented behaviour
	 * that also the filled_polygon should paint with patterns ... */
	CONTEXT_fill(style);
}

/* **************
 * CONTEXT_fill *
 * **************
 *
 * Filling routine, yet another undocumented feature of Gnuplot.
 * The code was mostly cloned from the PostScript terminal,
 * so that you know whom to accuse if it doesn't do what you would expect
 * it to do. (In case of cloning errors please inform the author of this terminal.)
 *
 * The lowest 4 bits of "style" seem to represent the style of filling
 * (whether it is solid or pattern-based or whatever that might appear
 * in that place in the future).
 *
 * The rest of the bits of "style" represent either the density
 * (ranging from 0 to 100) or the number of the pattern that the polygon
 * should be filled with.
 *
 * Used by CONTEXT_fillbox(...) and CONTEXT_filled_polygon(...)
 */
TERM_PUBLIC void
CONTEXT_fill(int style)
{
	int density;
	int pattern;

	/* used in FS_[TRANSPARENT_]SOLID --> fill with intensity according to filldensity 
	   it extracts a percentage out of "style" */
	density = (style >> 4);
	if (density < 0)
		density = 0;
	if (density > 100)
		density = 100;

	fputs("gp_fill(p", gpoutfile);

	/* do some strange trickery */
	switch (style & 0xf) {

	case FS_DEFAULT:
		break;

	case FS_TRANSPARENT_SOLID:
		/* just a flag to tell the terminal that density() should be used to interpret transparency */
		fprintf(gpoutfile, ",transparent");
	case FS_SOLID:
		/* fill the box with density "density": if no parameter density is specified,
		   it implies 100% density by default */
		if (density < 100)
			fprintf(gpoutfile, ",density(%.2f)", 0.01*density);
		break;

	case FS_TRANSPARENT_PATTERN:
		/* just a flag that should be interpreted in metapost,
		   non-transparent patterns have to fill with background color before drawing the pattern */
		fprintf(gpoutfile, ",transparent");
	case FS_PATTERN:
		pattern = (style >> 4);
		fprintf(gpoutfile, ",pattern(%d)", pattern);
		break;

	default: /* style == 0 (FS_EMPTY) or unknown --> fill with background color */
		fprintf(gpoutfile, ",density(0)");
	}
	/* TODO: FS_DEFAULT is missing; what should that one do? */

	/* gp_fill(p,...); */
	fputs(");\n", gpoutfile);
}

/* *******************
 * CONTEXT_linewidth *
 * *******************
 *
 * scale line width (similar to pointsize)
 * remembers the values locally (no serious need for that actually) and writes them into file
 */
TERM_PUBLIC void
CONTEXT_linewidth(double linewidth)
{
	if (linewidth < 0)
		linewidth = 1.0;
	
	if (CONTEXT_old_linewidth != linewidth) {
		/* close and draw the current path first */
		if (CONTEXT_path_count > 0)
			CONTEXT_endpath();
		fprintf(gpoutfile, "gp_set_linewidth(%.3f);\n", linewidth);
		CONTEXT_old_linewidth = linewidth;
	}
}

/* ------------------------------
 * CONTEXT_write_palette_gradient
 * ------------------------------
 *
 * Writes the colors and positions for a gradient pallete.
 */
static void
CONTEXT_write_palette_gradient(gradient_struct *gradient, int cnt)
{
	int i;
	
	/* i-th color */
	fprintf(gpoutfile, "colors(");
	for (i = 0; i < cnt; i++) {
		if (i > 0)
		    fprintf(gpoutfile, ",");
		fprintf(gpoutfile, "(%.3g,%.3g,%.3g)", gradient[i].col.r, gradient[i].col.g, gradient[i].col.b);
	}
	
	/* position of the i-th color */
	fprintf(gpoutfile, ");positions(");
	for (i = 0; i < cnt; i++) {
		if (i > 0)
			fprintf(gpoutfile, ",");
		fprintf(gpoutfile, "%.4g", gradient[i].pos);
	}
	fprintf(gpoutfile, ")");
}

/* ---------------------
 * CONTEXT_write_palette
 * ---------------------
 *
 */
static void
CONTEXT_write_palette(t_sm_palette *palette)
{
	if (palette == NULL)
		return;

/* TODO
	// Color models: RGB, HSV, CMY, YIQ, XYZ
	//
	// RGB: Red, Green, Blue
	// HSV: Hue, Saturation, Value
	// CMY
	//
	// two models that gnuplot uses, but which probably won't be supported by this terminal:
	// YIQ: U.S. Commercial Television Briadcasting (almost RGB)
	// XYZ: three primary colors of the color model defined by the 'Commission Internationale de l'Eclairage' (CIE)
	// http://www.cs.rit.edu/~ncs/color/glossary.htm
	// http://cs.fit.edu/wds/classes/cse5255/cse5255/davis/index.html
*/
	fprintf(gpoutfile, "gp_make_palette(");
	switch (sm_palette.colorMode) {
		/* grayscale only */
		case SMPAL_COLOR_MODE_GRAY:
			fprintf(gpoutfile, "color_mode(gray)");
			break;
		/* one of several fixed transformations */
		case SMPAL_COLOR_MODE_RGB:
			fprintf(gpoutfile, "color_mode(rgb);formulae(%d,%d,%d)",
				sm_palette.formulaR,
				sm_palette.formulaG,
				sm_palette.formulaB);
			break;
		/* user defined transforms */
		case SMPAL_COLOR_MODE_FUNCTIONS:
			fprintf(gpoutfile, "color_mode(functions)");
			break;
		/* interpolated table: explicitely defined or read from file */
		case SMPAL_COLOR_MODE_GRADIENT:
			fprintf(gpoutfile, "color_mode(gradient);");
			CONTEXT_write_palette_gradient(palette->gradient, palette->gradient_num);
			break;
		case SMPAL_COLOR_MODE_NONE:
			break;
		default:
			break;
	}
	fprintf(gpoutfile, ");\n");
}

/* *********************
 * CONTEXT_make_palette*
 * *********************
 *
 * 1. if palette==NULL, then return nice/suitable
 *    maximal number of colours supported by this terminal.
 *    Returns 0 if it can make colours without palette (like
 *    postscript).
 * 2. if palette!=NULL, then allocate its own palette
 *    return value is undefined
 * 3. available: some negative values of max_colors for whatever
 *    can be useful
 */
TERM_PUBLIC int
CONTEXT_make_palette(t_sm_palette *palette)
{
	if (palette == NULL)
		return 0;  /* ConTeXt can do continuous colors */

	/* save the palette */
	CONTEXT_old_palette = palette;
	
	return 0;
}


/*
 * most probably this one is not needed
 *
 * TERM_PUBLIC void
 * CONTEXT_previous_palette(){}
 *
 */

/* *******************
 * CONTEXT_set_color *
 * *******************
 *
 * typedef struct t_colorspec {
 *    int    type;    // TC_ DEFAULT, LT, LINESTYLE, RGB, CB, FRAC, Z
 *    int    lt;      // used for TC_LT, TC_LINESTYLE and TC_RGB
 *    double value;   // used for TC_CB and TC_FRAC
 * } t_colorspec;
 */
TERM_PUBLIC void
CONTEXT_set_color(t_colorspec *colorspec)
{
	double gray, r, g, b;
	/* ConTeXt doesn't offer full support for palettes yet
	   (I don't know how to trick metapost to accept the full palette specification)
	   so we convert the colors from palettes to RGB instead.
	   If terminal starts supporting palettes, this behaviour will change.
	*/
	rgb_color rgb1;

/* If (colorspec->type == TC_FRAC):
   Set current color according to colorspec->value, where 0 <= value <= 1.
   If using a palette, first map value to an integer i in the interval
   [0...num_colors-1], then set to the ith color in the palette.
   If (colorspec->type == TC_RGB):
   Set current color to the rgb triple given in colorspec->lt. */

	/* close and draw the current path first */
	if (CONTEXT_path_count > 0)
		CONTEXT_endpath();

	switch (colorspec->type) {

	/* TC_DEFAULT, TC_CB, TC_Z: probably unused; what about linestyle? */

	/* color equal as that of linetype in colorspec->lt */
	case TC_LT:
		fprintf(gpoutfile, "gp_set_color(lt(%d));\n", colorspec->lt);
		CONTEXT_color_changed = TRUE;
		break;

	/* rgb color */
	case TC_RGB:
		r = (double)((colorspec->lt >> 16 ) & 255) / 255.;
		g = (double)((colorspec->lt >> 8 ) & 255) / 255.;
		b = (double)(colorspec->lt & 255) / 255.;

		fprintf(gpoutfile, "gp_set_color(rgb(%3.2f,%3.2f,%3.2f));\n", r, g, b);
		CONTEXT_color_changed = TRUE;
		break;

	/* map [0:1] to gray colors or to the corresponding color from the palette */
	case TC_FRAC:
		gray = colorspec->value;

		/* limit negative and >1 values to [0:1] first */
		if (gray < 0) gray = 0;
		if (gray > 1) gray = 1;

		/* TODO: if ConTeXt start supporting palettes, we'll uncomment the following: */
		fprintf(gpoutfile, "%%gp_set_color(frac(%.4f));\n", gray);
		/* but now it doesn't, so let's use the fallback instead: */
		rgb1maxcolors_from_gray(gray, &rgb1);
		fprintf(gpoutfile, "gp_set_color(rgb(%3.2f,%3.2f,%3.2f));\n", rgb1.r, rgb1.g, rgb1.b);

		CONTEXT_color_changed = TRUE;
		break;
	default:
		int_warn(NO_CARET,"context.trm set_color unknown colorspec->type %i", colorspec->type);
		break;
	}
}


/* ************************
 * CONTEXT_filled_polygon *
 * ************************
 *
 * Draws a polygon with the fill color set by set_color, and no border.
 */
TERM_PUBLIC void
CONTEXT_filled_polygon(int points, gpiPoint *corners)
{
	int i;

	/* nothing to be filled if less than 3 points */
	if (points < 3)
		return;

	/* close and draw the current path first */
	if (CONTEXT_path_count > 0)
		CONTEXT_endpath();

	/* if the first point equals the last one, skip the last point; --cycle does that already
	 * this condition is probably always true in gnuplot, so the if condition may not be needed */
	if ((corners[0].x == corners[points-1].x) && (corners[0].y == corners[points-1].y))
		points--;

	/* create new path with corners */
	fputs("p := ", gpoutfile);
	fprintf(gpoutfile, "(%.3fa,%.3fa)", 0.001*corners[0].x, 0.001*corners[0].y);
	for (i = 1; i < points; i++) {
		if (i % CONTEXT_LINEMAX == 0)
			fputs("\n  ", gpoutfile);
		fprintf(gpoutfile, "--(%.3fa,%.3fa)", 0.001*corners[i].x, 0.001*corners[i].y);
	}
	/* and fill it */
	fprintf(gpoutfile, "--cycle;\n");

	/* fill the polygon
	 * undocumented gnuplot behaviour, copied from PostScript terminal
	 * see comments for CONTEXT_fill for details */
	CONTEXT_fill(corners->style);
}

/* ***************
 * CONTEXT_image *
 * ***************
 *
   Plot a pixel-based image on the display device.
   'M' is the number of pixels along the y-dimension of the image and
   'N' is the number of pixels along the x-dimension of the image.  The
   coordval pointer 'image' is the pixel values normalized to the range
   [0:1].  These values should be scaled appropriately for the output
   device.  The 'image' data starts in the upper left corner and scans
   along rows finishing in the lower right corner.  If 'color_mode' is
   IC_PALETTE, the terminal is to use palette lookup to generate color
   information.  In this scenario the size of 'image' is M*N.  If
   'color_mode' is IC_RGB, successive bytes of the data structure are 
   interpreted as RGB components of a single pixel.  In this scenario
   the size of 'image' is 3*M*N.  The data appears in RGB triples, i.e.,
   image[0] = R(1,1), image[1] = G(1,1), image[2] = B(1,1), 
   image[3] = R(1,2), image[4] = G(1,2), ..., image[3*M*N-1] = B(M,N).
   The mode IC_RGBA is similar except that four values red, green, blue,
   alpha per pixel are passed to the terminal in the image structure.
   The 'image' is actually an "input" image in the sense that
   it must also be properly resampled for the output device.  Many output
   media, e.g., PostScript, do this work via various driver functions.
   To determine the appropriate rescaling, the 'corner' information
   should be used.  There are four entries in the gpiPoint data array.
   'corner[0]' is the upper left corner (in terms of plot location) of
   the outer edge of the image.  Similarly, 'corner[1]' is the lower
   right corner of the outer edge of the image.  (Outer edge means the
   outer extent of the corner pixels, not the middle of the corner
   pixels.)  'corner[2]' is the upper left corner of the visible part
   of the image, and 'corner[3]' is the lower right corner of the visible
   part of the image.  The information is provided in this way because
   often it is necessary to clip a portion of the outer pixels of the
   image.
 */

/* TODO: this code needs some improvements
 *
 * There are two different modes:
 *
 * 1. creating PNG image and including it
 *    - it only works if gnuplot has been compiled with cairo or gdlib libraries
 *    - there are some bugs in MKII/MKIV handling: a different syntax is required
 *      and can only be fixed in ConTeXt core; I could abstract the code a bit
 * 2. printing out a string with colors
 *    - MKIV: works, but transparency is not yet implemented
 *    - MKII: requires MetaPost > 0.750 and is not implemented at all
 *            two possible approaches: drawing rectangles & creating proper image
 *            it might require one additional level of abstraction like gp_image(...)
 */
TERM_PUBLIC void
CONTEXT_image(unsigned M, unsigned N, coordval *image, gpiPoint *corner, t_imagecolor color_mode)
{
	int i, k, line_length, components_per_color;
	rgb_color color;
	TBOOLEAN is_clipped = FALSE;

	if ((corner[2].x > corner[0].x) || (corner[0].y > corner[2].y) ||
	    (corner[1].x > corner[3].x) || (corner[3].y > corner[1].y))
		is_clipped = TRUE;

	if (CONTEXT_images == CONTEXT_IMAGES_EXTERNAL) {
#ifdef WRITE_PNG_IMAGE
		/* we reserved 10 extra bytes, so we can afford images up to 9999 */
		snprintf(CONTEXT_image_filename + CONTEXT_image_filename_length, 9, "_%02d.png", ++CONTEXT_image_counter);
		write_png_image (M, N, image, color_mode, CONTEXT_image_filename);

		if (is_clipped)
			fprintf(gpoutfile, "draw image(\n  ");
		fprintf(gpoutfile, "externalfigure \"%s\" xyscaled (%.3fa,%.3fa) shifted (%.3fa,%.3fa);\n",
			CONTEXT_image_filename + CONTEXT_image_filename_start, 0.001*(corner[1].x-corner[0].x), 0.001*(corner[0].y-corner[1].y), 0.001*corner[0].x, 0.001*corner[1].y);
		if (is_clipped) {
			fprintf(gpoutfile, "  clip currentpicture to unitsquare xyscaled (%.3fa,%.3fa) shifted (%.3fa,%.3fa););\n",
				0.001*(corner[3].x-corner[2].x), 0.001*(corner[2].y-corner[3].y), 0.001*corner[2].x, 0.001*corner[3].y);
		}
#endif
	} else {

		/* Palette colors have to be converted into RGB first */
		if (color_mode == IC_PALETTE) {
			/* write the image data */
			fprintf(gpoutfile, "img := \"%%\n");
			line_length = 0;
			for (i = 0; i < M * N; i++) {
				if (line_length++ >= 16) {
					line_length = 1;
					fprintf(gpoutfile, "%%\n");
				}
				rgb1maxcolors_from_gray(image[i], &color);
				fprintf(gpoutfile, "%02x%02x%02x", (unsigned char)(255*color.r), (unsigned char)(255*color.g), (unsigned char)(255*color.b));
			}
			fprintf(gpoutfile, "\";\n");

		/* IC_RGB or IC_RGBA */
		} else {
			if (color_mode == IC_RGBA) {
				components_per_color = 4;
			} else { /* IC_RGB */
				components_per_color = 3;
			}

			/* write the image data */
			fprintf(gpoutfile, "img := \"%%\n");
			line_length = 0;
			for (i = 0; i < M * N; i++) {
				if (line_length++ >= 16) {
					line_length = 1;
					fprintf(gpoutfile, "%%\n");
				}
				for (k = 0; k < 3; k++) {
					fprintf(gpoutfile, "%02x", (unsigned char)(image[i*components_per_color+k]*255));
				}
			}
			fprintf(gpoutfile, "\";\n");

			/* transparency mask */
			if (color_mode == IC_RGBA) {
				fprintf(gpoutfile, "ima := \"%%\n");
				line_length = 0;
				for (i = 0; i < M * N; i++) {
					if (line_length++ >= 3*16) {
						line_length = 1;
						fprintf(gpoutfile, "%%\n");
					};
					fprintf(gpoutfile, "%02x", (unsigned char)(image[i*components_per_color+3]*255));
				}
				fprintf(gpoutfile, "\";\n");
			}
		}

		/* TODO: transparency handling is not yet supported in ConTeXt */
		if (is_clipped)
			fprintf(gpoutfile, "draw image(\n  ");
		fprintf(gpoutfile, "draw bitmapimage (%u,%u,img) xyscaled (%.3fa,%.3fa) shifted (%.3fa,%.3fa);\n",
			N, M, 0.001*(corner[1].x-corner[0].x), 0.001*(corner[0].y-corner[1].y), 0.001*corner[0].x, 0.001*corner[1].y);
		if (is_clipped) {
			fprintf(gpoutfile, "  clip currentpicture to unitsquare xyscaled (%.3fa,%.3fa) shifted (%.3fa,%.3fa););\n",
				0.001*(corner[3].x-corner[2].x), 0.001*(corner[2].y-corner[3].y), 0.001*corner[2].x, 0.001*corner[3].y);
		}

		/* (alternative implementation) *
		fprintf(gpoutfile, "gp_image_rgb");
		if (color_mode == IC_RGB)
			fprintf(gpoutfile, "_alpha");
		fprintf(gpoutfile, "((%u,%u),(%.3fa,%.3fa),(%.3fa,%.3fa));\n",
			N, M, 0.001*corner[0].x, 0.001*corner[1].y, 0.001*corner[1].x, 0.001*corner[0].y);
		*/
	}
}

/*
 * TODO: Implement this function for smooth shading
 *
 * you need to fix draw_color_smooth_box(MODE_SPLOT) in graph3d.c -> color.c
 *
static void
CONTEXT_draw_inside_color_smooth_box()
{
}
 */

#endif /* TERM_BODY */

#ifdef TERM_TABLE

TERM_TABLE_START(context_driver)
	"context", "ConTeXt with MetaFun (for PDF documents)",
	CONTEXT_XMAX, CONTEXT_YMAX, CONTEXT_VCHAR, CONTEXT_HCHAR,
	CONTEXT_VTIC, CONTEXT_HTIC, CONTEXT_options, CONTEXT_init,
	CONTEXT_reset, CONTEXT_text, null_scale, CONTEXT_graphics,
	CONTEXT_move, CONTEXT_vector,
	CONTEXT_linetype, CONTEXT_put_text, CONTEXT_text_angle,
	CONTEXT_justify_text, CONTEXT_point, CONTEXT_arrow, CONTEXT_set_font,
	CONTEXT_pointsize,
	/* also add TERM_CAN_CLIP once you understand what it does */
	TERM_CAN_DASH | TERM_ALPHA_CHANNEL | TERM_LINEWIDTH | TERM_FONTSCALE | TERM_IS_LATEX /* flags */,
	0 /* suspend */, 0 /* resume*/,
	CONTEXT_fillbox, CONTEXT_linewidth
#ifdef USE_MOUSE
	, 0, 0, 0, 0, 0 /* no mouse support */
#endif /* USE_MOUSE */
	, CONTEXT_make_palette,
	0, /* XXX: CONTEXT_previous_palette: not sure if we need it at all (PS does "grestore") */
	CONTEXT_set_color,
	CONTEXT_filled_polygon,
	CONTEXT_image,
	0, 0, 0, /* No enhanced text mode because this is TeX */
	0,       /* layer (used to signal front/back text, used in canvas, PS, epslatex, ...); XXX: figure out what this has to do */
	0        /* path (Path control for end-joins of closed polygons on PostScript-like devices); TODO: implement it (CONTEXT_path) */
TERM_TABLE_END(context_driver)
#undef LAST_TERM
#define LAST_TERM context_driver

#endif /* TERM_TABLE */
#endif /* TERM_PROTO_ONLY */

#ifdef TERM_HELP
START_HELP(context)
"1 context",
"?commands set terminal context",
"?set terminal context",
"?terminal context",
"?set term context",
"?term context",
"?context",
" ConTeXt is a macro package for TeX, highly integrated with Metapost",
" (for drawing figures) and intended for creation of high-quality PDF documents.",
" The terminal outputs Metafun source, which can be edited manually,",
" but you should be able to configure most things from outside.",
"",
" For an average user of ConTeXt + gnuplot module it's recommended to refer to",
" `Using ConTeXt` rather than reading this page",
" or to read the manual of the gnuplot module for ConTeXt.",
"",
" The `context` terminal supports the following options:",
"",
" Syntax:",
"      set term context {default}",
"              {defaultsize | size <scale> | size <xsize>{in|cm}, <ysize>{in|cm}}",
"              {input | standalone}",
"              {timestamp | notimestamp}",
"              {noheader | header \"<header>\"}",
"              {color | colour | monochrome}",
"              {rounded | mitered | beveled} {round | butt | squared}",
"              {dashed | solid} {dashlength | dl <dl>}",
"              {linewidth | lw <lw>}",
"              {fontscale <fontscale>}",
"              {mppoints | texpoints}",
"              {inlineimages | externalimages}",
"              {defaultfont | font \"{<fontname>}{,<fontsize>}\"}",
"",
" In non-standalone (`input`) graphic only parameters `size` to select graphic",
" size, `fontscale` to scale all the labels for a factor <fontscale>",
" and font size, make sense, the rest is silently",
" ignored and should be configured in the .tex file which inputs the graphic.",
" It's highly recommended to set the proper fontsize if document font differs from",
" 12pt, so that gnuplot will know how much space to reserve for labels.",
"",
" `default` resets all the options to their default values.",
"",
" `defaultsize` sets the plot size to 5in,3in.",
" `size` <scale> sets the plot size to <scale> times <default value>.",
" If two arguments are given (separated with ','), the first one sets",
" the horizontal size and the second one the vertical size.",
" Size may be given without units (in which case it means relative to the default",
" value), with inches ('in') or centimeters ('cm').",
"",
" `input` (default) creates a graphic that can be included into another ConTeXt",
" document.",
" `standalone` adds some lines, so that the document might be compiled as-is.",
" You might also want to add `header` in that case.",
"",
" Use `header` for any additional settings/definitions/macros",
" that you might want to include in a standalone graphic. `noheader` is the default.",
"",
" `notimestamp` prevents printing creation time in comments",
" (if version control is used, one may prefer not to commit new version when only date changes).",
"",
" `color` to make color plots is the default, but `monochrome` doesn't do anything special yet.",
" If you have any good ideas how the behaviour should differ to suit the monochrome printers better,",
" your suggestions are welcome.",
"",
" `rounded` (default), `mitered` and `beveled` control the shape of line joins.",
" `round` (default), `butt` and `squared` control the shape of line caps.",
" See PostScript or PDF Reference Manual for explanation. For wild-behaving functions",
" and thick lines",
" it is better to use `rounded` and `round` to prevent sharp corners in line joins.",
" (Some general support for this should be added to Gnuplot, so that the same options",
" could be set for each line (style) separately).",
"",
" `dashed` (default) uses different dash patterns for different line types,",
" `solid` draws all plots with solid lines.",
"",
" `dashlength` or `dl` scales the length of the dashed-line segments by <dl>.",
" `linewidth` or `lw` scales all linewidths by <lw>.",
" (lw 1 stands for 0.5bp, which is the default line width when drawing with Metapost.)",
" `fontscale` scales text labels for factor <fontscale> relative to default document font.",
"",
" `mppoints` uses predefined point shapes, drawn in Metapost.",
" `texpoints` uses easily configurable set of symbols, defined with ConTeXt",
" in the following way:",
"      \\defineconversion[my own points][+,{\\ss x},\\mathematics{\\circ}]",
"      \\setupGNUPLOTterminal[context][points=tex,pointset=my own points]",
"",
" `inlineimages` writes binary images to a string and only works in ConTeXt MKIV.",
" `externalimages` writes PNG files to disk and also works with ConTeXt MKII.",
" Gnuplot needs to have support for PNG images built in for this to work.",
"",
" With `font` you can set font name and size in standalone graphics.",
" In non-standalone (`input`) mode only the font size is important",
" to reserve enough space for text labels.",
" The command",
"      set term context font \"myfont,ss,10\"",
" will result in",
"      \\setupbodyfont[myfont,ss,10pt]",
" If you additionally set `fontscale` to 0.8 for example,",
" then the resulting font will be 8pt big and",
"      set label ... font \"myfont,12\"",
" will come out as 9.6pt.",
"",
" It is your own responsibility to provide proper typescripts (and header),",
" otherwise switching the font will have no effect.",
" For a standard font in ConTeXt MKII (pdfTeX) you could use:",
"      set terminal context standalone header '\\usetypescript[iwona][ec]' \\",
"          font \"iwona,ss,11\"",
" Please take a look into ConTeXt documentation, wiki or mailing list (archives)",
" for any up-to-date information about font usage.",
"",
" Examples:",
"      set terminal context size 10cm, 5cm     # 10cm, 5cm",
"      set terminal context size 4in, 3in      # 4in, 3in",
" For standalone (whole-page) plots with labels in UTF-8 encoding:",
"      set terminal context standalone header '\\enableregime[utf-8]'",
"", /* TODO: LaTeX formatting */
"2 Requirements",
" You need gnuplot module for ConTeXt",
"^ <a href=\"http://ctan.org/pkg/context-gnuplot\">",
"      http://ctan.org/pkg/context-gnuplot",
"^ </a>",
" and a recent version of ConTeXt.",
" If you want to call gnuplot on-the-fly, you also need write18 enabled.",
" In most TeX distributions this can be set with shell_escape=t in texmf.cnf.",
"",
" See",
"^ <a href=\"http://wiki.contextgarden.net/Gnuplot\">",
"           http://wiki.contextgarden.net/Gnuplot",
"^ </a>",
" for details about this terminal and for more exhaustive help & examples.",
"",
"2 Calling gnuplot from ConTeXt",
" The easiest way to make plots in ConTeXt documents is",
"      \\usemodule[gnuplot]",
"      \\starttext",
"      \\title{How to draw nice plots with {\\sc gnuplot}?}",
"      \\startGNUPLOTscript[sin]",
"      set format y \"%.1f\"",
"      plot sin(x) t '$\\sin(x)$'",
"      \\stopGNUPLOTscript",
"      \\useGNUPLOTgraphic[sin]",
"      \\stoptext",
" This will run gnuplot automatically and include the resulting figure in the document."
END_HELP(context)
#endif /* TERM_HELP */