File: gd.trm

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

/* GNUPLOT -- gd.trm */

/*[
 * Copyright 1998, 2001, 2004
 *
 * 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 file is included by ../term.c.
 *
 * This terminal driver supports PNG and JPEG output using
 *  GD library version 2
 *
 * To Use:
 *
 * set terminal png ?options ...?
 *
 * Where an option is:
 *
 * transparent - generate transparent PNGs.  The first color will
 * be the transparent one.
 *
 * interlace - generate interlaced PNGs.
 *
 * image size (in pixels)
 *
 * font size (tiny,small,medium,large,giant)
 *
 * font name (TrueType or Adobe Type 1 font name is passed to libgd)
 *
 * EAM Dec 2010: Obsolete!
 * xrrggbb - sets the next color.  x is the literal character 'x',
 * rrggbb are the red green and blue components in hex.  For example
 * x00ff00 is green.  The background color is set first, then the
 * color borders, then the X & Y axis, then the plotting colors.
 * (The wierd color spec is in order to get around limitations
 * in gnuplot's scanner.)
 *
 * This driver is modeled after the PBM driver pbm.trm.
 *
 * AUTHORS
 *  Sam Shen <sls@mh1.lbl.gov>
 *  Alex Woo <woo@playfair.stanford.edu>
 *  Ethan A Merritt <merritt@u.washington.edu>
 *
 * CONTRIBUTORS
 *  Alfred Reibenschuh <alfred.reibenschuh@it-austria.com> or <fredo@blackbox.at>
 *  Ben Laurie <ben@algroup.co.uk>
 *
 * This version outputs either indexed or truecolor (24-bit RGB) images
 * The default size is 640x480 pixels.
 *
 ******************************************************************************
 * PLEASE READ                                                                *
 * This driver uses the gd library, available from http://www.libgd.org       *
 * This driver allows you to use TrueType, OpenType, or Adobe Type 1 fonts.   *
 * If you have libgd version 2.0.36 or later, you may also be able to access  *
 * any fonts that are managed by the fontconfig utility.                      *
 * You can use this driver without having any TrueType fonts installed,       *
 * but the default fonts are comparatively limited.                           *
 ******************************************************************************
 *
 * Petr Mikulik, Jan 1999: terminal entries for PM3D functionality
 * Ethan Merritt, May 2001: modified gd/gif driver to produce png instead;
 *                          added support for line width and TrueType fonts
 * Shige Takeno, Mar 2011: deal with libgd built to use SJIS rather than UTF-8
 * Ethan Merritt, Apr 2012: Don't claim to support versions 1.x of libgd
 */

#define GD_DEFINED_COLORS	96	/* Must not exceed size of pm3d_color_names_tbl[] */

#include "driver.h"

#ifdef TERM_REGISTER
register_term(png)
#endif

#ifdef TERM_PROTO
TERM_PUBLIC void PNG_options __PROTO((void));
TERM_PUBLIC void PNG_init __PROTO((void));
TERM_PUBLIC void PNG_graphics __PROTO((void));
TERM_PUBLIC void PNG_text __PROTO((void));
TERM_PUBLIC void PNG_linetype __PROTO((int linetype));
TERM_PUBLIC void PNG_linewidth __PROTO((double linewidth));
TERM_PUBLIC void PNG_move __PROTO((unsigned int x, unsigned int y));
TERM_PUBLIC void PNG_vector __PROTO((unsigned int x, unsigned int y));
TERM_PUBLIC void PNG_put_text __PROTO((unsigned int x, unsigned int y, const char str[]));
TERM_PUBLIC int PNG_justify_text __PROTO((enum JUSTIFY mode));
TERM_PUBLIC void PNG_point __PROTO((unsigned int x, unsigned int y, int number));
TERM_PUBLIC int PNG_text_angle __PROTO((int ang));
TERM_PUBLIC void PNG_reset __PROTO((void));
TERM_PUBLIC int PNG_set_font __PROTO((const char *fontname));
TERM_PUBLIC void PNG_pointsize __PROTO((double ptsize));
TERM_PUBLIC void PNG_boxfill(int, unsigned int, unsigned int, unsigned int, unsigned int);
TERM_PUBLIC int PNG_make_palette (t_sm_palette *);
/* TERM_PUBLIC void PNG_previous_palette (void); */
TERM_PUBLIC void PNG_set_color (t_colorspec *);
TERM_PUBLIC void PNG_filled_polygon (int, gpiPoint *);
TERM_PUBLIC void PNG_image __PROTO((unsigned int, unsigned int, coordval *, gpiPoint *, t_imagecolor));

/* To support "set term png enhanced" */
TERM_PUBLIC void ENHGD_put_text __PROTO((unsigned int x, unsigned int y, const char str[]));
TERM_PUBLIC void ENHGD_OPEN __PROTO((char * fontname, double fontsize,
			double base, TBOOLEAN widthflag, TBOOLEAN showflag,
			int overprint));
TERM_PUBLIC void ENHGD_FLUSH __PROTO((void));

#ifdef EAM_BOXED_TEXT
TERM_PUBLIC void ENHGD_boxed_text __PROTO((unsigned int, unsigned int, int));
#endif

#include <gd.h>
/* Include files for bitmap fonts */
#include <gdfontt.h>
#include <gdfonts.h>
#include <gdfontl.h>
#include <gdfontmb.h>
#include <gdfontg.h>

/* Before version 2.0.36, the libgd function gdFTUseFontConfig() didn't */
/* do what we need.  Test for earlier versions and ignore it.           */
#ifdef GD_MAJOR_VERSION
#  if (GD_MINOR_VERSION > 0  ||  GD_RELEASE_VERSION > 35)
#    define gdUseFontConfig(x) gdFTUseFontConfig(x)
#  endif
#endif
#ifndef gdUseFontConfig
#define gdUseFontConfig(x) 0
#endif

/* These intermediate functions are necessary on Windows since 
   the shared version of libgd uses a different calling convention
   and there is no proper macro defined.
*/
#if defined(WIN32) && !defined(NONDLL)
static void gp_gdImagePolygon(gdImagePtr, gdPointPtr, int, int);
static void gp_gdImageFilledPolygon(gdImagePtr, gdPointPtr, int, int);
#else
# define gp_gdImagePolygon gdImagePolygon
# define gp_gdImageFilledPolygon gdImageFilledPolygon 
#endif

static void PNG_PointX __PROTO((unsigned int, unsigned int));
static void PNG_PointPlus __PROTO((unsigned int, unsigned int));
static void PNG_Triangle(unsigned int x, unsigned int y, int direction,
	void (*draw_func)(gdImagePtr, gdPointPtr, int, int));
static void PNG_Diamond(unsigned int x, unsigned int y,
	void (*draw_func)(gdImagePtr, gdPointPtr, int, int));
static void PNG_init_brush __PROTO((int));

#define GREG_XMAX 640
#define GREG_YMAX 480

/* This will be the default font */
# define gdfont gdFontMediumBold
# define PNG_VCHAR 13
# define PNG_HCHAR 7

#define PNG_TICSIZE (GREG_YMAX/100)

#define PNG_MAX_COLORS 256
#define GOT_NEXT_PROTO
#endif

#ifndef TERM_PROTO_ONLY
#ifdef TERM_BODY

static TBOOLEAN PNG_initialized = FALSE;	/* Set when terminal first initialized */

static struct {
    gdImagePtr image;
    gdFontPtr font;
    unsigned int x, y;
    int height;
    int charh, charw;
    int color;             /* Magic index returned by libgd */
    int rgb;               /* Our guess at the corresponding rgb */
    int n_colors;
    int color_table[PNG_MAX_COLORS];
    int rgb_table[PNG_MAX_COLORS];
    int angle;
    enum JUSTIFY justify;
    int flags;
    int linetype;
    int linewidth;
    TBOOLEAN capbutt;  /* use capbutt on lines with GD2, 20051205 MWS*/
    TBOOLEAN use_builtin;
    int ttfsize;
    char *ttffont;
    gdFontPtr default_font;
    char *    default_ttffont;
    int       default_ttfsize;
    double    fontscale;
    TBOOLEAN  TrueColor;
    /* Variables for animated gif support: */
    TBOOLEAN  animate;		/* Only gif supports animation */
    int       loop_count;	/* Number of times to repeat sequence */
    int       frame_count;	/* Number of frames in animation */
    int       frame_delay;	/* Time between frames in .01 seconds */
    TBOOLEAN  frame_optimization;
    gdImagePtr previous_image;	/* Needed to encode animation as a series of deltas */
} png_state;

#define PNG_USE_TRANSPARENT 1
#define PNG_USE_INTERLACE   2
#define PNG_USE_CROP        4

enum PNG_id {
    PNG_TRANSPARENT, PNG_NOTRANSPARENT,
    PNG_INTERLACE, PNG_NOINTERLACE,
    PNG_CROP, PNG_NOCROP,
    /* Font size */
    PNG_TINY, PNG_SMALL, PNG_MEDIUM, PNG_LARGE, PNG_GIANT,
    PNG_FONT, PNG_FONTSCALE,
    PNG_SIZE, PNG_BACKGROUND,
    PNG_ENHANCED, PNG_NOENHANCED,
    PNG_TRUECOLOR, PNG_NOTRUECOLOR,
    PNG_LINEWIDTH, PNG_BUTT, PNG_ROUNDED, PNG_DASHLENGTH,
    GIF_ANIMATE, GIF_DELAY, GIF_LOOP, GIF_NOOPT, GIF_OPT,
    PNG_OTHER
};

#ifdef Y
#   undef Y
#endif
#define Y(y) (png_state.height - (y))

static int PNG_XMAX = GREG_XMAX;
static int PNG_YMAX = GREG_YMAX;
static const int PNG_POINT_SCALE = 3;
static int PNG_ps = 3;

#ifdef EAM_BOXED_TEXT
    unsigned int bounding_box[4];
#define GD_TEXTBOX_MARGIN 1.0
    double bounding_xmargin = GD_TEXTBOX_MARGIN;
    double bounding_ymargin = GD_TEXTBOX_MARGIN;
#endif

static TBOOLEAN ENHgd_show = TRUE;
static TBOOLEAN ENHgd_sizeonly = FALSE;

static struct gen_table PNG_opts[] =
{
    { "trans$parent", PNG_TRANSPARENT },
    { "notran$sparent", PNG_NOTRANSPARENT },
    { "inter$lace", PNG_INTERLACE },
    { "nointer$lace", PNG_NOINTERLACE },
    { "crop", PNG_CROP },
    { "nocrop", PNG_NOCROP },
    { "ti$ny", PNG_TINY },
    { "s$mall", PNG_SMALL },
    { "m$edium", PNG_MEDIUM },
    { "l$arge", PNG_LARGE },
    { "g$iant", PNG_GIANT },
    { "fontscale", PNG_FONTSCALE },
    { "fo$nt", PNG_FONT },
    { "si$ze", PNG_SIZE },
    { "enh$anced", PNG_ENHANCED },
    { "noenh$anced", PNG_NOENHANCED },
    { "true$color", PNG_TRUECOLOR },
    { "notrue$color", PNG_NOTRUECOLOR },
    { "linew$idth", PNG_LINEWIDTH },
    { "anim$ate", GIF_ANIMATE }, /* gif animation options */
    { "delay", GIF_DELAY },
    { "loop", GIF_LOOP },
    { "noopt$imize", GIF_NOOPT },
    { "opt$imize", GIF_OPT }, /* end of gif animation options */
    { "lw", PNG_LINEWIDTH },
    { "butt", PNG_BUTT},
    { "round$ed", PNG_ROUNDED},
    { "dashl$ength", PNG_DASHLENGTH},
    { "dl", PNG_DASHLENGTH},
    { "backg$round", PNG_BACKGROUND},
    { NULL, PNG_OTHER }
};

#undef MAXLINEWIDTH
#define MAXLINEWIDTH 100
static double PNG_linewidth_factor = 1.0;
static double PNG_dashlength_factor = 1.0;

/* shige takeno: 
 * libgd can be built to prefer UTF-8 or SJIS encoding for Japanese.
 * If it wants SJIS and we are currently in UTF8, convert.
 * If it wants UTF8 and we are currently in SJIS, convert.
 * conditional compilation flags:
 *   HAVE_ICONV (iconv library)
 *   JIS_GDLIB (using gdlib configured with -DJISX0208)
 */
#ifdef HAVE_ICONV
#include <iconv.h>
#endif
static void gd_iconv __PROTO((char **string));

/* EAM - gdImage structure to hold brushes for linewidth */
/* We will allocate and initialize these on demand */
typedef struct {
    gdImagePtr im;
    unsigned int last_rgb;
    int bgnd;
    int fgnd;
}   PNG_BRUSH;

static PNG_BRUSH *PNG_brush[MAXLINEWIDTH+1];

typedef struct {
    gdImagePtr im;
    unsigned int last_rgb;
    int fillpar;
}   PNG_FILL_TILE;

static PNG_FILL_TILE PNG_fill_tile = { (gdImagePtr)0, 0, 0 };

/* To be used with libgd 2.0.34 to request Symbol encoding */
#ifdef gdFTEX_Adobe_Custom
static gdFTStringExtra PNG_FONT_INFO = {0,0,0,0,0,NULL,NULL};
#endif

#if defined(WIN32) && !defined(NONDLL)
static void 
gp_gdImagePolygon(gdImagePtr im, gdPointPtr p, int n, int c)
{
    gdImagePolygon(im, p, n, c);
}

static void 
gp_gdImageFilledPolygon(gdImagePtr im, gdPointPtr p, int n, int c)
{
    gdImageFilledPolygon(im, p, n, c);
}
#endif


/* Common code to crop the image around its bounding box, just before writing
   down the file.
*/
static void
image_do_crop ()
{
    if (png_state.flags & PNG_USE_CROP) {
	int x, y, x1, y1, x2, y2, flag;
	int bg = png_state.color_table[0]; /* index of the background color */
	gdImagePtr im_crop;
	for (flag=0, x1=0; x1 < gdImageSX(png_state.image)-1; x1++) {
	    for (y=0; y < gdImageSY(png_state.image); y++)
		if (gdImageGetPixel(png_state.image, x1, y) != bg) { flag = 1; break; }
	    if (flag) break;
	}
	for (flag=0, x2=gdImageSX(png_state.image)-1; x2 >= x1; x2--) {
	    for (y=0; y < gdImageSY(png_state.image); y++)
		if (gdImageGetPixel(png_state.image, x2, y) != bg) { flag = 1; break; }
	    if (flag) break;
	}
	for (flag=0, y1=0; y1 < gdImageSY(png_state.image)-1; y1++) {
	    for (x=x1; x <= x2; x++)
		if (gdImageGetPixel(png_state.image, x, y1) != bg) { flag = 1; break; };
	    if (flag) break;
	}
	for (flag=0, y2=gdImageSY(png_state.image)-1; y2 >= y1; y2--) {
	    for (x=x1; x <= x2; x++)
		if (gdImageGetPixel(png_state.image, x, y2) != bg) { flag = 1; break; };
	    if (flag) break;
	}
	x = x2 - x1 + 1; /* width */
	y = y2 - y1 + 1; /* height */

	if (png_state.TrueColor)
	    im_crop = gdImageCreateTrueColor(x,y);
	else
	    im_crop = gdImageCreate(x,y);
	if (!im_crop) {
	    int_warn(NO_CARET,"libgd: failed to create cropped image structure");
	    return;
	}
	bg = gdImageColorAllocateAlpha(im_crop,255,255,255,127);

	gdImagePaletteCopy(im_crop, png_state.image);
	if (png_state.flags & PNG_USE_TRANSPARENT) {
	    gdImageColorTransparent(im_crop, bg);
	    /* WARNING: This is a work-around for strangeness in libgd,  */
	    /* which doesn't copy transparent pixels in TrueColor images. */
	    if (png_state.TrueColor)
		gdImageColorTransparent(png_state.image, -1);
	} else
	    gdImageColorTransparent(im_crop, -1);

	gdImageCopy(im_crop, png_state.image, 0, 0, x1, y1, x, y);
	gdImageDestroy(png_state.image);
	png_state.image = im_crop;
    }
}


static int PNG_FillSolid __PROTO((int fillpar));
static int PNG_FillPattern __PROTO((int fillpar));
static int PNG_FillTransparent __PROTO((int fillpar));

static int
PNG_FillSolid(int fillpar)
{
    int red   = (png_state.rgb >> 16) & 0xff;
    int green = (png_state.rgb >> 8) & 0xff;
    int blue  = png_state.rgb & 0xff;

    double fact = (double)(100 - fillpar) * 0.01;

    int color;

    if (fact <= 0 || fact >= 1.0)
	return png_state.color;

    red   += (0xff - red) * fact;
    green += (0xff - green) * fact;
    blue  += (0xff - blue) * fact;

    color = gdImageColorExact(png_state.image, red, green, blue);
    if (color < 0) {
	color = gdImageColorAllocate(png_state.image, red, green, blue);
    }
    if (color < 0) {
	color = gdImageColorClosest(png_state.image, red, green, blue);
    }

    return color;
}

static int
PNG_FillTransparent(int fillpar)
{
    int red   = (png_state.rgb >> 16) & 0xff;
    int green = (png_state.rgb >> 8) & 0xff;
    int blue  = png_state.rgb & 0xff;
    int alpha = 127 * (float)(100-fillpar) / 100.;

    return  gdImageColorExactAlpha(png_state.image, red, green, blue, alpha);
}

static int
PNG_FillPattern(int style)
{
    int rgb = png_state.rgb;
    int brgb = png_state.rgb_table[0];
    int fillpar = (style >> 4) % 8;
    style = style & 0xf;

    if (!PNG_fill_tile.im || rgb != PNG_fill_tile.last_rgb || PNG_fill_tile.fillpar != fillpar) {

	int foreground, background;

	if (PNG_fill_tile.im) {
	    gdImageDestroy(PNG_fill_tile.im);
	    PNG_fill_tile.im = (gdImagePtr)0;
	}

	/* save new values */
	PNG_fill_tile.fillpar = fillpar;
	PNG_fill_tile.last_rgb = rgb;

	/* create new tile */
	if (!((PNG_fill_tile.im = gdImageCreate(8, 8))))
	    int_error(NO_CARET,"libgd: failed to create pattern-fill tile");

	background = gdImageColorAllocate(PNG_fill_tile.im,
		(brgb >> 16) & 0xff, (brgb >> 8) & 0xff, brgb & 0xff);
	if (style == FS_TRANSPARENT_PATTERN)
	    gdImageColorTransparent(PNG_fill_tile.im, background);
	gdImageFilledRectangle(PNG_fill_tile.im, 0, 0, 7, 7, background);

	/* foreground */
	foreground = gdImageColorAllocate(PNG_fill_tile.im,
		(rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff);

	switch (fillpar) {
	    case 0: /* no fill */
	    default:
		break;
	    case 1: /* cross-hatch */
		gdImageLine(PNG_fill_tile.im, 0, 0, 7, 7, foreground);
		gdImageLine(PNG_fill_tile.im, 0, 6, 6, 0, foreground);
		break;
	    case 2: /* double cross-hatch */
		gdImageLine(PNG_fill_tile.im, 0, 0, 7, 7, foreground);
		gdImageLine(PNG_fill_tile.im, 0, 6, 6, 0, foreground);
		gdImageLine(PNG_fill_tile.im, 0, 2, 2, 0, foreground);
		gdImageLine(PNG_fill_tile.im, 7, 3, 3, 7, foreground);
		gdImageLine(PNG_fill_tile.im, 4, 0, 7, 3, foreground);
		gdImageLine(PNG_fill_tile.im, 0, 4, 3, 7, foreground);
		break;
	    case 3: /* solid */
		gdImageFilledRectangle(PNG_fill_tile.im, 0, 0, 7, 7, foreground);
		break;
	    case 4:
		gdImageLine(PNG_fill_tile.im, 0, 0, 7, 7, foreground);
		break;
	    case 5:
		gdImageLine(PNG_fill_tile.im, 0, 7, 7, 0, foreground);
		break;
	    case 6:
		gdImageLine(PNG_fill_tile.im, 0, 0, 3, 7, foreground);
		gdImageLine(PNG_fill_tile.im, 4, 0, 7, 7, foreground);
		break;
	    case 7:
		gdImageLine(PNG_fill_tile.im, 0, 7, 3, 0, foreground);
		gdImageLine(PNG_fill_tile.im, 4, 7, 7, 0, foreground);
		break;
	    case 8:
		gdImageLine(PNG_fill_tile.im, 0, 0, 7, 3, foreground);
		gdImageLine(PNG_fill_tile.im, 0, 4, 7, 7, foreground);
		break;
	    case 9:
		gdImageLine(PNG_fill_tile.im, 0, 3, 7, 0, foreground);
		gdImageLine(PNG_fill_tile.im, 0, 7, 7, 4, foreground);
		break;
	}
    }

    gdImageSetTile(png_state.image, PNG_fill_tile.im);
    return (int)gdTiled;
}

static void
PNG_PointX(unsigned int x, unsigned int y)
{
    gdImageLine(png_state.image, x - PNG_ps, y - PNG_ps,
	    x + PNG_ps, y + PNG_ps, png_state.color);
    gdImageLine(png_state.image, x + PNG_ps, y - PNG_ps,
	    x - PNG_ps, y + PNG_ps, png_state.color);
}

static void
PNG_PointPlus(unsigned int x, unsigned int y)
{
    gdImageLine(png_state.image, x - PNG_ps, y,
	    x + PNG_ps, y, png_state.color);
    gdImageLine(png_state.image, x, y - PNG_ps,
	    x, y + PNG_ps, png_state.color);
}

static void
PNG_Triangle(
    unsigned int x, unsigned int y,
    int direction,
    void (*draw_func)(gdImagePtr, gdPointPtr, int, int))
{
    int delta  = (int)((1.33 * (double)PNG_ps) + 0.5);
    int delta_ = (int)((0.67 * (double)PNG_ps) + 0.5);

    gdPoint points[4];
    points[0].x = x;
    points[0].y = y - direction * delta;
    points[1].x = x - delta;
    points[1].y = y + direction * delta_;
    points[2].x = x + delta;
    points[2].y = y + direction * delta_;
    points[3].x = points[0].x;
    points[3].y = points[0].y;
    draw_func(png_state.image, points, 4, png_state.color);
}

static void
PNG_Diamond(
    unsigned int x, unsigned int y,
    void (*draw_func)(gdImagePtr, gdPointPtr, int, int))
{
    gdPoint points[5];
    points[0].x = x;
    points[0].y = y - PNG_ps;
    points[1].x = x + PNG_ps;
    points[1].y = y;
    points[2].x = x;
    points[2].y = y + PNG_ps;
    points[3].x = x - PNG_ps;
    points[3].y = y;
    points[4].x = points[0].x;
    points[4].y = points[0].y;
    draw_func(png_state.image, points, 5, png_state.color);
}

/*
 * _options()  Called when terminal type is selected.
 * This procedure should parse options on the command line.  A list of the
 * currently selected options should be stored in term_options[] in a form
 * suitable for use with the set term command.  term_options[] is used by
 * the save command.  Use options_null() if no options are available.
 */
TERM_PUBLIC void
PNG_options()
{
    int i;
    char *string;
    unsigned long color;
    TBOOLEAN gif_anim_option = FALSE; /* set to TRUE if an animated gif option given */

    if (!PNG_initialized) {
	PNG_initialized = TRUE;
	term_options[0] = '\0';
	term->h_char = PNG_HCHAR; /* Default to medium font */
	png_state.default_font = gdfont;
	png_state.n_colors = 0;
	png_state.flags = 0;
	png_state.use_builtin = FALSE;
	png_state.ttffont = NULL;
	png_state.default_ttffont = NULL;
	png_state.default_ttfsize = 0;
	png_state.fontscale = 1;
	png_state.justify = CENTRE;
	png_state.TrueColor = FALSE;
	PNG_linewidth_factor = 1.0;
	PNG_dashlength_factor = 1.0;
	png_state.capbutt = FALSE; /* to preserve previous default behavior */
#ifdef _Windows
	/* Set the default search path for fonts to something useful. */
	if (getenv("GDFONTPATH") == NULL) {
	    const char fonts[] = "\\fonts";
	    char *windir = getenv("windir");
	    if (windir) {
		char *gdfontpath = (char *)
		    gp_alloc(strlen(windir) + strlen(fonts) + 1, "GDFONTPATH");
		if (gdfontpath) {
		   strcpy(gdfontpath, windir);
		   strcat(gdfontpath, fonts);
		   SetEnvironmentVariable("GDFONTPATH", gdfontpath);
		   free(gdfontpath);
		}
	    }
	}
#endif
    } else {
	/* FIXME EAM - these should never happen! */
	if (!png_state.default_font) {
	    fprintf(stderr,"gd.trm: caught initialization error\n");
	    png_state.default_font = gdfont;
	}
    }

    /* Annoying hack to handle the case of 'set termoption' after */
    /* we are already in animation mode.                          */
    if (almost_equals(c_token-1, "termopt$ion"))
	FPRINTF((stderr,"gif: Maintaining animation state\n"));
    else {
	/* Otherwise reset animation parameters */
	if (png_state.previous_image)
	    gdImageDestroy(png_state.previous_image);
	png_state.animate = FALSE;
	png_state.previous_image = NULL;
	png_state.frame_optimization = FALSE;
	png_state.loop_count = 0;
	/* And default font size */
	term->h_char = PNG_HCHAR;
	png_state.default_ttfsize = 0;
	PNG_linewidth_factor = 1.0;
	PNG_dashlength_factor = 1.0;
	/* Default to enhanced text */
	term->flags |= TERM_ENHANCED_TEXT;
	term->put_text = ENHGD_put_text;
    }

    while (!END_OF_COMMAND) {
	switch(lookup_table(&PNG_opts[0],c_token)) {
	case PNG_TRANSPARENT:
	    png_state.flags |= PNG_USE_TRANSPARENT;
	    ++c_token;
	    break;
	case PNG_NOTRANSPARENT:
	    png_state.flags &= ~PNG_USE_TRANSPARENT;
	    ++c_token;
	    break;
	case PNG_INTERLACE:
	    png_state.flags |= PNG_USE_INTERLACE;
	    ++c_token;
	    break;
	case PNG_NOINTERLACE:
	    png_state.flags &= ~PNG_USE_INTERLACE;
	    ++c_token;
	    break;
	case PNG_CROP:
	    png_state.flags |= PNG_USE_CROP;
	    ++c_token;
	    break;
	case PNG_NOCROP:
	    png_state.flags &= ~PNG_USE_CROP;
	    ++c_token;
	    break;

#ifdef HAVE_GD_TTF
# define UNSET_TTF_FONT \
	    free(png_state.ttffont); \
	    png_state.ttffont = NULL; \
	    png_state.default_ttfsize = 2 * term->h_char - 2; \
	    png_state.use_builtin = TRUE;
#else
# define UNSET_TTF_FONT \
	    ; /* nothing to do */
#endif

	case PNG_TINY:
	    png_state.default_font = gdFontGetTiny();
	    term->v_char = png_state.default_font->h;
	    term->h_char = png_state.default_font->w;
	    ++c_token;
	    UNSET_TTF_FONT;
	    break;
	case PNG_SMALL:
	    png_state.default_font = gdFontGetSmall();
	    term->v_char = png_state.default_font->h;
	    term->h_char = png_state.default_font->w;
	    ++c_token;
	    UNSET_TTF_FONT;
	    break;
	case PNG_MEDIUM:
	    png_state.default_font = gdFontGetMediumBold();
	    term->v_char = png_state.default_font->h;
	    term->h_char = png_state.default_font->w;
	    ++c_token;
	    UNSET_TTF_FONT;
	    break;
	case PNG_LARGE:
	    png_state.default_font = gdFontGetLarge();
	    term->v_char = png_state.default_font->h;
	    term->h_char = png_state.default_font->w;
	    ++c_token;
	    UNSET_TTF_FONT;
	    break;
	case PNG_GIANT:
	    png_state.default_font = gdFontGetGiant();
	    term->v_char = png_state.default_font->h;
	    term->h_char = png_state.default_font->w;
	    ++c_token;
	    UNSET_TTF_FONT;
	    break;

	case PNG_FONT:
	    c_token++;
#ifdef HAVE_GD_TTF
	    if (END_OF_COMMAND) {
		free(png_state.ttffont);
		png_state.ttffont = NULL;
		png_state.default_ttfsize = 0;
	    } else {
		int brect[8];
		char *err;

		if (isstringvalue(c_token)) {
		    char *s = try_to_get_string();
		    char *comma = strrchr(s,',');
		    double fontsize;
		    if (comma && (1 == sscanf(comma+1,"%lf",&fontsize))) {
			png_state.default_ttfsize = (int)(fontsize+0.5);
			png_state.ttfsize = png_state.default_ttfsize;
			*comma = '\0';
		    }
		    if (*s) {
			free(png_state.ttffont);
			png_state.ttffont = s;
		    } else {
			continue;
		    }
		} else {
		    free(png_state.ttffont);
		    png_state.ttffont = gp_alloc(token_len(c_token)+1,"new font");
		    copy_str(png_state.ttffont, c_token, token_len(c_token)+1);
		    c_token++;
		}
		free(png_state.default_ttffont);
		png_state.default_ttffont = gp_strdup(png_state.ttffont);

		/* First try the old GDFONTPATH mechanism for locating fonts */
		(void)gdUseFontConfig(0);
		err = gdImageStringFT(NULL, &brect[0], 0,
			png_state.ttffont, (double)png_state.default_ttfsize*png_state.fontscale,
			0.0, 0, 0, "test");
	
		/* If that didn't work, try again using the fontconfig mechanism */
		if (err && gdUseFontConfig(1)) {
		    err = gdImageStringFT(NULL, &brect[0], 0,
			png_state.ttffont, (double)png_state.default_ttfsize*png_state.fontscale,
			0.0, 0, 0, "test");
		}

		/* If we still haven't found the font, punt to the internal non-TTF default set */
		if (err) {
		    fprintf(stderr, "%s when opening font %s, trying default\n",
				err, png_state.ttffont);
		    free(png_state.ttffont);
		    free(png_state.default_ttffont);
		    png_state.ttffont = NULL;
		    png_state.default_ttffont = NULL;
		}

	    }
#else
	    c_token++;
	    fprintf(stderr,"No TTF font support, using internal non-scalable font\n");
#endif
	    break;
# undef UNSET_TTF_FONT

	case PNG_FONTSCALE:
	    c_token++;
	    png_state.fontscale = END_OF_COMMAND ? 1 : real_expression();
	    if (png_state.fontscale <= 0)
		png_state.fontscale = 1.;
	    break;

	case PNG_SIZE:
	    c_token++;
	    if (END_OF_COMMAND) {
		PNG_XMAX = GREG_XMAX;
		PNG_YMAX = GREG_YMAX;
	    } else {
		PNG_XMAX = real_expression();
		if (equals(c_token, ",")) {
		    c_token++;
		    PNG_YMAX = real_expression();
		}
		if (PNG_XMAX <= 0)
		    PNG_XMAX = GREG_XMAX;
		if (PNG_YMAX <= 0)
		    PNG_YMAX = GREG_YMAX;
	    }
	    term->ymax = PNG_YMAX;
	    term->xmax = PNG_XMAX;
	    /* EAM Apr 2003 - same tic size on both x and y axes */
	    term->v_tic = (PNG_XMAX < PNG_YMAX) ? PNG_XMAX/100 : PNG_YMAX/100;
	    if (term->v_tic < 1)
		term->v_tic = 1;
	    term->h_tic = term->v_tic;
	    break;
	case PNG_ENHANCED:
	    term->flags |= TERM_ENHANCED_TEXT;
	    term->put_text = ENHGD_put_text;
	    ++c_token;
	    break;
	case PNG_NOENHANCED:
	    term->flags &= ~TERM_ENHANCED_TEXT;
	    term->put_text = PNG_put_text;
	    ++c_token;
	    break;
	case PNG_TRUECOLOR:
	    png_state.TrueColor = TRUE;
	    term->flags |= TERM_ALPHA_CHANNEL;
	    c_token++;
	    break;
	case PNG_NOTRUECOLOR:
	    png_state.TrueColor = FALSE;
	    term->flags &= ~TERM_ALPHA_CHANNEL;
	    c_token++;
	    break;
	case PNG_LINEWIDTH:
	    c_token++;
	    PNG_linewidth_factor = real_expression();
	    if (PNG_linewidth_factor < 0)
		PNG_linewidth_factor = 1.0;
	    break;
	case PNG_DASHLENGTH:
	    c_token++;
	    PNG_dashlength_factor = real_expression();
	    if (PNG_dashlength_factor <= 0.2)
		PNG_dashlength_factor = 1.0;
	    break;

	/* parse gif animation options */
	case GIF_ANIMATE:
	    if (strncmp("gif",term->name,3))
		int_error(c_token,"Only the gif terminal supports animation");
	    c_token++;
	    png_state.animate = TRUE;
	    png_state.frame_count = 0;
	    png_state.frame_delay = 10;
	    png_state.frame_optimization = FALSE;
	    gif_anim_option = 1;
	    break;
	case GIF_DELAY:
	    if (strncmp("gif",term->name,3))
		int_error(c_token,"Only the gif terminal supports animation");
	    c_token++;
	    png_state.frame_delay = int_expression();
	    if (png_state.frame_delay <= 0)
		png_state.frame_delay = 10;
	    gif_anim_option = 1;
	    break;
	case GIF_LOOP:
	    if (strncmp("gif",term->name,3))
		int_error(c_token,"Only the gif terminal supports animation");
	    c_token++;
	    png_state.loop_count = int_expression();
	    gif_anim_option = 1;
	    break;
	case GIF_NOOPT:
	    if (strncmp("gif",term->name,3))
		int_error(c_token,"Only the gif terminal supports animation");
	    c_token++;
	    png_state.frame_optimization = FALSE;
	    gif_anim_option = 1;
	    break;
	case GIF_OPT:
	    if (strncmp("gif",term->name,3))
		int_error(c_token,"Only the gif terminal supports animation");
	    c_token++;
	    png_state.frame_optimization = TRUE;
	    gif_anim_option = 1;
	    break;

	case PNG_BUTT:
	    png_state.capbutt = TRUE;
	    c_token++;
	    break;

	case PNG_ROUNDED:
	    png_state.capbutt = FALSE;
	    c_token++;
	    break;

	case PNG_BACKGROUND:
	    c_token++;
	    png_state.rgb_table[0] = parse_color_name();
	    png_state.n_colors = 1;
	    break;

	case PNG_OTHER:
	default:
	    /* not "size" */
	    string = gp_input_line + token[c_token].start_index;

#ifdef HAVE_GD_TTF
	    /* Check for explicit TTF font size */
	    if (sscanf(string, "%d", &i) == 1) {
		if (i > 0 && i < 999)
		    png_state.default_ttfsize = i;
		else
		    int_warn(c_token,"illegal font size");
		c_token++;
	        break;
	    }
#endif

	    if (sscanf(string, "x%lx", &color) == 1)
		int_error(c_token, "obsolete color option");
	    else
		int_error(c_token, "unrecognized terminal option");
	    break;
	}
    }

    if (gif_anim_option) {
#ifndef GIF_ANIMATION /* animated gifs not supported by the current GD library */
	png_state.animate = FALSE;
	int_warn(NO_CARET, "gif animation options ignored (not compiled into this binary)");
#endif
    }

#ifdef HAVE_GD_TTF
    /* If no font has been chosen but there is a default, use it */
    if (!png_state.ttffont && !png_state.use_builtin) {
	char *external_default = getenv("GNUPLOT_DEFAULT_GDFONT");
	int brect[8];
	char *err;

	if (external_default)
		png_state.ttffont = gp_strdup(external_default);
	else	/* Might as well try some plausible font; it's no worse than failing immediately */
		png_state.ttffont = gp_strdup("/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf");

	free(png_state.default_ttffont);
	png_state.default_ttffont = gp_strdup(png_state.ttffont);
	if (png_state.default_ttfsize == 0)
		png_state.default_ttfsize = 2 * term->h_char - 2;

	/* First try the old GDFONTPATH mechanism for locating fonts */
	(void)gdUseFontConfig(0);
	err = gdImageStringFT(NULL, &brect[0], 0,
		png_state.ttffont, (double)png_state.default_ttfsize*png_state.fontscale,
		0.0, 0, 0, "test");

	/* If that didn't work, try again using fontconfig mechanism */
	if (err && gdUseFontConfig(1)) {
	    err = gdImageStringFT(NULL, &brect[0], 0,
		png_state.ttffont, (double)png_state.default_ttfsize*png_state.fontscale,
		0.0, 0, 0, "test");
	}

	/* If we still haven't found the font, punt to the internal non-TTF default set */
	if (err) {
		fprintf(stderr,"%s when opening font \"%s\", using internal non-scalable font\n",
			err, png_state.ttffont);
		free(png_state.ttffont);
		free(png_state.default_ttffont);
		png_state.ttffont = NULL;
		png_state.default_ttffont = NULL;
	}

    }

    /* If no explicit TTF font size found, generate default */
    if (!(png_state.default_ttfsize > 0))
	png_state.default_ttfsize = 2 * term->h_char - 2;
    png_state.ttfsize = png_state.default_ttfsize;

    /* Find approximate character width of selected TTF font   */
    /* This is needed in order to set appropriate border width */
    if (png_state.default_ttffont) {
	int brect[8];
	char *err;
	err = gdImageStringFT(NULL, &brect[0], 0,
		png_state.default_ttffont, (double)png_state.default_ttfsize*png_state.fontscale,
		0.0, 0, 0, "f00000000g");
	if (!err) {
	    term->h_char = .11 * (float)(brect[2] - brect[0]) + 0.5;
	    term->v_char = 1.1 * (float)(brect[1] - brect[7]) + 0.5;
	}
    }
#endif

    /* This code is shared by png, gif, and jpeg terminal types */
    if (!strcmp(term->name,"jpeg"))
	png_state.flags &= ~PNG_USE_TRANSPARENT;

    /* now generate options string */

    if (png_state.flags & PNG_USE_TRANSPARENT) {
	strcat(term_options, "transparent ");
    }
    if (png_state.flags & PNG_USE_INTERLACE) {
	strcat(term_options, "interlace ");
    }
    /* JPEG files are always 24-bit color */
    if (strcmp(term->name, "jpeg") == 0) {
	png_state.TrueColor = TRUE;
	term->flags |= TERM_ALPHA_CHANNEL;
    } else if (png_state.TrueColor) {
	strcat(term_options, "truecolor ");
    }
    if (!(png_state.flags & PNG_USE_CROP)) {
	strcat(term_options, "no");
    }
    strcat(term_options, "crop ");

    if (term->flags & TERM_ENHANCED_TEXT) {
	strcat(term_options, "enhanced ");
    }

    if (PNG_linewidth_factor != 1.0)
	sprintf(term_options + strlen(term_options),
	    "linewidth %3.1f ", PNG_linewidth_factor);

    if (PNG_dashlength_factor != 1.0)
	sprintf(term_options + strlen(term_options),
	    "dashlength %3.1f ", PNG_dashlength_factor);

    if (png_state.capbutt) {
	sprintf(term_options + strlen(term_options),
	    "butt ");
    }

    if (png_state.animate) {
	sprintf(term_options + strlen(term_options),
	    "animate delay %d loop %d %soptimize ", 
	    png_state.frame_delay, png_state.loop_count,
	    png_state.frame_optimization ? "" : "no");
    }

    sprintf(term_options + strlen(term_options),
	    "size %d,%d ", PNG_XMAX, PNG_YMAX);

    if (png_state.n_colors == 1)
	sprintf(term_options + strlen(term_options),
	    "background \"#%06x\" ", png_state.rgb_table[0]);

    if (png_state.ttffont) {
	if (png_state.fontscale != 1.0)
	    sprintf(term_options + strlen(term_options),
		"fontscale %.1f ", png_state.fontscale);
	if (strlen(term_options) + strlen(png_state.ttffont) < sizeof(term_options) - 32)
	    sprintf(term_options + strlen(term_options),
		"font \"%s,%d\" ", png_state.ttffont, png_state.ttfsize);
    } else switch (term->h_char) {
    case 5:
	strcat(term_options,"tiny ");
	break;
    case 6:
	strcat(term_options, "small ");
	break;
    case 7:
    default:
	strcat(term_options, "medium ");
	break;
    case 8:
	strcat(term_options, "large ");
	break;
    case 9:
	strcat(term_options,"giant ");
	break;
    }

}


/*
 * _init()  Called once, when the device is first selected.  This procedure
 * should set up things that only need to be set once, like handshaking and
 * character sets etc...
 */
TERM_PUBLIC void
PNG_init()
{
int i;

    png_state.linetype = 0;
    png_state.linewidth = 1;

    /* Clear brush array, then initialize a few small ones */
    for (i=2; i<=MAXLINEWIDTH; i++)
	PNG_brush[i] = NULL;
}

/*
 * Internal helper routine to initialize brushes used for stroking linewidth > 1
 */
static void
PNG_init_brush(int width)
{
    PNG_BRUSH *brush = PNG_brush[width];

    if (!brush) {
	brush = gp_alloc(sizeof(PNG_BRUSH),"gd brush");
	PNG_brush[width] = brush;
	brush->last_rgb = -99;  /* Something invalid */
	if (!((brush->im = gdImageCreate(width,width))))
	    int_error(NO_CARET,"libgd: failed to create brush structure");
	brush->bgnd = gdImageColorAllocate( brush->im, 255, 255, 255 );
	gdImageFill(brush->im, 0, 0, brush->bgnd);
	gdImageColorTransparent(brush->im, brush->bgnd);
    }

    if (png_state.color != brush->last_rgb) {
	brush->fgnd = gdImageColorResolve(brush->im,
	    gdImageRed(png_state.image,png_state.color),
	    gdImageGreen(png_state.image,png_state.color),
	    gdImageBlue(png_state.image,png_state.color) );
	brush->last_rgb = png_state.color;

	/* EAM - quick and dirty is to fill the entire brush (square nib)  */
	/* It might be better to approximate a circular nib by selectively */
	/* coloring the individual pixels of the brush image.          	   */
	gdImageFilledRectangle(brush->im, 0, 0, width-1, width-1, brush->fgnd);
    }
}

/*
 * _reset()  Called when gnuplot is exited, the output device changed or
 * the terminal type changed.  This procedure should reset the device,
 * possibly flushing a buffer somewhere or generating a form feed.
 */
TERM_PUBLIC void
PNG_reset()
{
    int i;
    /* EAM - Clean up the brushes used for linewidth */
    for (i=2; i<=MAXLINEWIDTH; i++) {
	if (PNG_brush[i]) {
	    if (PNG_brush[i]->im)
		gdImageDestroy(PNG_brush[i]->im);
	    PNG_brush[i] = NULL;
	}
    }
    if (PNG_fill_tile.im) {
	gdImageDestroy(PNG_fill_tile.im);
	PNG_fill_tile.im = (gdImagePtr)0;
    }
#ifdef GIF_ANIMATION
    if (png_state.animate) {
	gdImageGifAnimEnd(gpoutfile);
	png_state.frame_count = 0;
	png_state.animate = FALSE;
	fprintf(stderr,"End of animation sequence\n");
    }
#endif
}

#if 0
/* use  #if 1  that's just for debugging */
void
PNG_show_current_palette()
{
    int i;

    fprintf(stderr, "*****\n SHOW THE PALETTE! total=%i\n",
	    gdImageColorsTotal(png_state.image));
    for (i=0; i < gdImageColorsTotal(png_state.image); i++) {
	/* Use access macros to learn colors. */
	fprintf(stderr, "%i\tr=%d\t g=%d\tb=%d\n",
		i,
		gdImageRed(png_state.image,i),
		gdImageGreen(png_state.image,i),
		gdImageBlue(png_state.image,i));
    }
}
#endif

/*
How this works: Gray interval [0;1] will be mapped to interval
[0;sm_palette.colors-1] those r,g,b components are mapped by the array
below palette.offset equals 0 since png_smooth_color[0..colors] are
from ColorAllocate
*/
static int png_smooth_color[gdMaxColors];

  /* TODO: how to recover from a multiplot with two colour pm3d maps?
     They must use the same palette! Or palette size must be
     restricted to certain number of colours---a new user's option
  */

TERM_PUBLIC int PNG_make_palette (t_sm_palette *palette)
{
    int i;
    if (palette == NULL) {
	/* If the output format is TrueColor there in no color limit */
	if (png_state.TrueColor)
	    return(0);

	/* return maximal number of colours in a PNG palette */
	i = gdMaxColors /*256*/ - gdImageColorsTotal(png_state.image);
	/* the latter is the number of currently allocated colours. We want
	   to allocate the rest */
	/*BACK PLEASE  fprintf(stderr,"colors in PNG palette=%i\n",(int)gdMaxColors); */
	if (i == 0) {
	    i = (sm_palette.colors <= 0) ? -1 : sm_palette.colors;
	        /* (no more colorus) : (previous palette (obviously multiplot mode)) */
	}
	return i;
    }
    if (0 == gdMaxColors /*256*/ - gdImageColorsTotal(png_state.image))
	return 0; /* reuse previous palette (without warning) */
    for (i = 0; i < sm_palette.colors; i++) {
	png_smooth_color[i] = gdImageColorAllocate(png_state.image,
	    (int)( palette->color[i].r * 255 + 0.5 ), /* r,g,b values for png */
	    (int)( palette->color[i].g * 255 + 0.5 ), /* terminal are [0;255] */
	    (int)( palette->color[i].b * 255 + 0.5 ) );
    }
    return 0;
}


TERM_PUBLIC
void PNG_set_color (t_colorspec *colorspec)
{
    double gray = colorspec->value;
    int save;

    switch (colorspec->type) {

    case TC_LT:
	save = png_state.linetype;
	PNG_linetype(colorspec->lt);
	png_state.linetype = save;
	break;

    case TC_RGB:
	png_state.rgb = colorspec->lt;
	if (png_state.TrueColor)
	    png_state.color = gdImageColorExactAlpha(png_state.image, 
		(colorspec->lt >> 16) & 0xff,
		(colorspec->lt >> 8) & 0xff, 
		 colorspec->lt & 0xff,
		(colorspec->lt >> 25) & 0x7f);
	else
	    png_state.color = gdImageColorResolve(png_state.image,
		(colorspec->lt >> 16) & 0xff,
		(colorspec->lt >> 8) & 0xff, 
		colorspec->lt & 0xff);
	break;

    case TC_FRAC:
	if (png_state.TrueColor) {
	    rgb255_color color;
	    rgb255maxcolors_from_gray(gray, &color);
	    png_state.color = gdImageColorResolve(png_state.image,
		(int)color.r, (int)color.g, (int)color.b);
	    png_state.rgb = (color.r << 16) + (color.g << 8) +color.b;
	    return;
	} else {
	    int png_color = (gray <= 0) ? 0 : (int)(gray * sm_palette.colors);
	    if (png_color >= sm_palette.colors)
		png_color = sm_palette.colors - 1;
	    /* map [0;1] to interval [0;png_smooth_colors-1] */
	    png_state.color = png_smooth_color[ png_color ];
	}
	break;

    default:
	break;
    }

    /* This is correct, but currently the resulting gdAntiAliased is not used */
    gdImageSetAntiAliased(png_state.image, png_state.color);
}

TERM_PUBLIC
void PNG_filled_polygon(int points, gpiPoint *corners)
{
    int i;
    int fillpar = corners->style >> 4;
    int color = png_state.color;
    
    /* since gpiPoint carries more than just x and y if
     * we have EXTENDED_COLOR_SPECS defined, we need to
     * copy it to the gdPointPtr struct; make it static
     * so that is faster (joze) */
    static gdPointPtr gd_corners = (gdPointPtr) 0;
    static unsigned int size = 0;
    if (points > size) {
	size = points;
	gd_corners = gp_realloc(gd_corners, sizeof(gdPoint) * size,
	    "PNG_filled_polygon->gd_corners");
    }
    for (i = 0; i < points; i++) {
	gd_corners[i].x = corners[i].x;
	gd_corners[i].y = Y(corners[i].y);
    }

    switch (corners->style & 0xf) {
	case FS_EMPTY: /* fill with background color */
	    color = png_state.color_table[0];
	    break;
	case FS_SOLID: /* solid fill */
	    color = PNG_FillSolid(fillpar);
	    break;
	case FS_TRANSPARENT_SOLID:
	    if (png_state.TrueColor)
		color = PNG_FillTransparent(fillpar);
	    else
		color = PNG_FillSolid(fillpar);
	    break;
	case FS_PATTERN: /* pattern fill */
	case FS_TRANSPARENT_PATTERN:
	    color = PNG_FillPattern(corners->style);
	    break;
	default:
	    color = png_state.color;
	    break;
    }

    gdImageFilledPolygon(png_state.image, gd_corners, points, color);
}

/*
 * This function is used for filledboxes
 * style parameter is some garbled hash combining fillstyle and filldensity
 */
TERM_PUBLIC void
PNG_boxfill(
    int style,
    unsigned int x, unsigned int y,
    unsigned int width, unsigned int height)
{
    unsigned int x1, y1, x2, y2;
    int          color;

    /* fillpar:
     * - solid   : 0 - 100
     * - pattern : 0 - 100
     */
    int fillpar = style >> 4;

    switch (style & 0xf) {
	case FS_EMPTY: /* fill with background color */
	    color = png_state.color_table[0];
	    break;
	case FS_SOLID: /* solid fill */
	    color = PNG_FillSolid(fillpar);
	    break;
	case FS_TRANSPARENT_SOLID:
	    if (png_state.TrueColor)
		color = PNG_FillTransparent(fillpar);
	    else
		color = PNG_FillSolid(fillpar);
	    break;
	case FS_PATTERN: /* pattern fill */
	case FS_TRANSPARENT_PATTERN:
	    color = PNG_FillPattern(style);
	    break;
	default:
	    /* should never happen */
	    color = png_state.color;
	    break;
    }

    x1 = x;
    x2 = x + width - 1;
    y2 = Y(y);
    y1 = y2 - height + 1;
    gdImageFilledRectangle(png_state.image, x1, y1, x2, y2, color);
}

/*
 * _graphics()  Called just before a plot is going to be displayed.  This
 * procedure should set the device into graphics mode.  Devices which can't
 * be used as terminals (like plotters) will probably be in graphics mode
 * always and therefore won't need this.
 */
TERM_PUBLIC void
PNG_graphics()
{
    int i;
    unsigned int rgb;
 
    for (i = png_state.n_colors; i < GD_DEFINED_COLORS; i++)
	png_state.rgb_table[i] = pm3d_color_names_tbl[i].value;
    if (png_state.n_colors < GD_DEFINED_COLORS)
	png_state.n_colors = GD_DEFINED_COLORS;

    /* TrueColor images default to a black background; load white instead.	*/
    /* If PNG_USE_TRANSPARENT, store the background alpha in the output file	*/
    /* but apply alpha for the rest of the image internally. Otherwise you	*/
    /* see only background through the topmost transparent layer.		*/
    if (png_state.TrueColor) {
        unsigned int brgb = png_state.rgb_table[0];
	png_state.image = gdImageCreateTrueColor(PNG_XMAX, PNG_YMAX);
	if (!png_state.image)
	    int_error(NO_CARET,"libgd: failed to create output image structure");
	if (png_state.flags & PNG_USE_TRANSPARENT) {
	    rgb = gdImageColorAllocateAlpha(png_state.image,
		(brgb >> 16) & 0xff, (brgb >> 8) & 0xff, brgb & 0xff, 127);
	    gdImageSaveAlpha(png_state.image, 1);
	    gdImageAlphaBlending(png_state.image, 0);
	} else {
	    rgb = gdImageColorAllocate(png_state.image,
		(brgb >> 16) & 0xff, (brgb >> 8) & 0xff, brgb & 0xff);
	}
	gdImageFill(png_state.image, 1, 1, rgb);
	gdImageAlphaBlending(png_state.image, 1);

    } else
	png_state.image = gdImageCreate(PNG_XMAX, PNG_YMAX);
    if (!png_state.image)
	int_error(NO_CARET,"libgd: failed to create output image structure");

    png_state.height = PNG_YMAX - 1;
    png_state.charw = term->h_char;	/* png_state.font->w; */
    png_state.charh = term->v_char;	/* png_state.font->h; */
    png_state.font = png_state.default_font;
    png_state.color = 0;

    for (i = 0; i < png_state.n_colors; i++) {
	rgb = png_state.rgb_table[i];
	png_state.color_table[i] =
	    gdImageColorAllocate(png_state.image, (rgb >> 16) & 0xff,
				 (rgb >> 8) & 0xff, rgb & 0xff);
    }
    if (png_state.flags & PNG_USE_TRANSPARENT)
	gdImageColorTransparent(png_state.image, png_state.color_table[0]);
    else
	gdImageColorTransparent(png_state.image, -1);

}

/*
 * _text()  Called immediately after a plot is displayed.  This procedure
 * should set the device back into text mode if it is also a terminal, so
 * that commands can be seen as they're typed.  Again, this will probably
 * do nothing if the device can't be used as a terminal.
 */
TERM_PUBLIC void
PNG_text()
{
    image_do_crop();
    if (png_state.flags & PNG_USE_INTERLACE)
	gdImageInterlace(png_state.image, 1);
    gdImagePng(png_state.image, gpoutfile);
    gdImageDestroy(png_state.image);
}

/* _move(x,y)  Called at the start of a line.  The cursor should move to the
 * (x,y) position without drawing.
 */
TERM_PUBLIC void
PNG_move(unsigned int x, unsigned int y)
{
    png_state.x = x;
    png_state.y = y;
}

/* _vector(x,y)  Called when a line is to be drawn.  This should display a line
 * from the last (x,y) position given by _move() or _vector() to this new (x,y)
 * position.
 */
TERM_PUBLIC void
PNG_vector(unsigned int x, unsigned int y)
{
    int lw = png_state.linewidth;

    /* Dashed line style; used only for the x/y grid */
    if (png_state.linetype == -1) {
	static int last_lw = -1;
	static double last_dl = -1;
	static int last_color = -1;
	static int *png_linetype_dotted = NULL;
	static int ssize;

	/* Adjust the style when linewidth or dashlength has changed. */
	if (lw != last_lw || PNG_dashlength_factor != last_dl || last_color != png_state.color) {
	    int i;
	    int dashlength = 2 * PNG_dashlength_factor;
	    int spacelength = 3 * PNG_dashlength_factor;
	    int psize = lw*lw*dashlength;
	    
	    ssize = lw*lw*(spacelength + dashlength);
	    png_linetype_dotted = gp_realloc( png_linetype_dotted, ssize*sizeof(int), "dashes");

	    /* Fill style with with color then transparent.
	     * The style is 2 on / 3 off and scales with linewidth and dashlength.
	     */
	    for(i = 0;i < psize; i++)
		png_linetype_dotted[i] = png_state.color;
	    for (;i < ssize; i++)
		png_linetype_dotted[i] = gdTransparent;
	    last_lw = lw;
	    last_dl = PNG_dashlength_factor;
	    last_color = png_state.color;
	}
	/* This driver does not in general use gd's built-in SetThickness command,
	 * because it only works right for purely horizontal or vertical lines.
	 * But that's OK for a 2D grid.
	 */
	gdImageSetStyle(png_state.image, png_linetype_dotted, ssize);
	gdImageSetThickness(png_state.image,lw);
	gdImageLine(png_state.image, png_state.x, Y(png_state.y), x, Y(y), gdStyled);
	gdImageSetThickness(png_state.image,1);

    /* All other (not dashed) vectors */
    } else {
	if (png_state.linewidth == 1) {
#if defined(gdAntiAliased) 
	    gdImageSetThickness(png_state.image,1);
	    gdImageSetAntiAliased(png_state.image, png_state.color);
	    gdImageLine(png_state.image, png_state.x, Y(png_state.y),
			x, Y(y), gdAntiAliased);
#else
	    gdImageLine(png_state.image, png_state.x, Y(png_state.y),
			x, Y(y), png_state.color);
#endif

	} else if (png_state.capbutt){

	    gdImageSetThickness(png_state.image,png_state.linewidth);
	    gdImageLine(png_state.image, png_state.x, Y(png_state.y),
			x, Y(y), png_state.color);

	} else {
	    /* EAM - Implement linewidth by using a brush */
	    PNG_init_brush(lw);
	    gdImageSetBrush(png_state.image, PNG_brush[lw]->im);
	    gdImageLine(png_state.image, png_state.x, Y(png_state.y),
			x, Y(y), gdBrushed );
	}
    }

    png_state.x = x;
    png_state.y = y;
}

/* _linetype(lt)  Called to set the line type before text is displayed or
 * line(s) plotted.
 * Negative linetypes are defined in gadgets.h
 * lt 0 and upwards are used for plots 0 and upwards.
 * If _linetype() is called with lt greater than the available line types,
 * it should map it to one of the available line types.
 */
TERM_PUBLIC void
PNG_linetype(int type)
{
    if (type >= (png_state.n_colors - 3))
	type %= (png_state.n_colors - 3);
    if (type <= LT_BACKGROUND) /* LT_NODRAW, LT_BACKGROUND, LT_UNDEFINED */
	type = -3;	/* Draw in background color */

    png_state.color = png_state.color_table[type + 3];
    png_state.rgb = png_state.rgb_table[type + 3];
    png_state.linetype = type;
}

/* Use the "brush" tools in the gd library to control line width.
 * Pre-define brushes for linewidths 2, 3, 4, 5, 6 (1 doesn't need a brush!).
 * Here we just remember the state.
 */
TERM_PUBLIC void
PNG_linewidth(double linewidth)
{
    png_state.linewidth = (int)(PNG_linewidth_factor * linewidth+0.49);
    if (png_state.linewidth > MAXLINEWIDTH) png_state.linewidth = MAXLINEWIDTH;
    if (png_state.linewidth < 1) png_state.linewidth = 1;
}

/* _put_text(x,y,str)  Called to display text at the (x,y) position,
 * while in graphics mode.   The text should be vertically (with respect
 * to the text) justified about (x,y).  The text is rotated according
 * to _text_angle and then horizontally (with respect to the text)
 * justified according to _justify_text.
 */
#ifdef HAVE_GD_TTF
TERM_PUBLIC void
PNG_put_text(unsigned int x, unsigned int y, const char *string)
{
    /* Mar 2011 - added to handle SJIS/UTF8 conversion */
    if (contains8bit(string)) {
	gd_iconv((char **)(&string));
    }

    if (png_state.ttffont) {
	int brect[8]; char *err;
	/* Draw once with a NULL image to get the bounding rectangle */
	/* then draw it again, centered.                             */
	err = gdImageStringFT(NULL, brect, png_state.color,
			png_state.ttffont, (double)png_state.ttfsize*png_state.fontscale,
			(double)png_state.angle * M_PI_2 / 90. ,
			x, Y(y), (char *)string);
	if (err) {
	    fprintf(stderr,"gdImageStringFT: %s while printing string %s with font %s\n",
		err,string,png_state.ttffont);
	} else {
	    x += sin((double)png_state.angle * M_PI_2/90.) * (double)png_state.charh/4.;
	    y -= cos((double)png_state.angle * M_PI_2/90.) * (double)png_state.charh/4.;
	    switch (png_state.justify) {
		case RIGHT:
				x -= (brect[2]-brect[0]);
				y += (brect[3]-brect[1]);
				break;
		case CENTRE:
				x -= (brect[2]-brect[0]) / 2.;
				y += (brect[3]-brect[1]) / 2.;
				break;
		case LEFT:
		default:	break;
	    }
	    err = gdImageStringFT(png_state.image, brect, png_state.color,
			png_state.ttffont, (double)png_state.ttfsize*png_state.fontscale,
			(double)png_state.angle * M_PI_2 / 90.,
			x, Y(y), (char *)string);
	    if (err)
		fprintf(stderr,"gdImageStringFT: %s while printing string %s with font %s\n",
		    err,string,png_state.ttffont);

#ifdef EAM_BOXED_TEXT
	    if (!ENHgd_sizeonly) {
		int xmax = GPMAX(brect[2],brect[6]);
		int xmin = GPMIN(brect[0],brect[4]);
		int ymax = GPMIN(brect[1],brect[3]);
		int ymin = GPMAX(brect[5],brect[7]);
		if (xmin < bounding_box[0]) bounding_box[0] = xmin;
		if (xmax > bounding_box[2]) bounding_box[2] = xmax;
		if (ymin < bounding_box[1]) bounding_box[1] = ymin;
		if (ymax > bounding_box[3]) bounding_box[3] = ymax;
	    }
#endif

	}
    } else if (png_state.angle != 0) {
	x -= png_state.charh / 2;
	switch (png_state.justify) {
	    case RIGHT:	y -= png_state.charw * strlen(string);
			break;
	    case CENTRE:y -= png_state.charw * strlen(string) / 2;
			break;
	    case LEFT:
	    default:	break;
	}
	gdImageStringUp(png_state.image, png_state.font,
			x, Y(y),
			(unsigned char *)string, png_state.color);
    } else {
	y += png_state.charh / 2;
	switch (png_state.justify) {
	    case RIGHT:	x -= png_state.charw * strlen(string);
			break;
	    case CENTRE:x -= png_state.charw * strlen(string) / 2;
			break;
	    case LEFT:
	    default:	break;
	}
	gdImageString(png_state.image, png_state.font,
		      x, Y(y),
		      (unsigned char *)string, png_state.color);
    }

}

#else  /* not HAVE_GD_TTF */

TERM_PUBLIC void
PNG_put_text(unsigned int x, unsigned int y, const char *string)
{
    if (png_state.angle == 0) {
	y += png_state.charh / 2;
	gdImageString(png_state.image, png_state.font,
		      x, Y(y),
		      (unsigned char *)string, png_state.color);
    } else {
	x -= png_state.charh / 2;
	gdImageStringUp(png_state.image, png_state.font,
			x, Y(y),
			(unsigned char *)string, png_state.color);
    }
}

#endif /* HAVE_GD_TTF */


TERM_PUBLIC int
PNG_text_angle(int ang)
{
    while (ang < -180) ang += 360;	/* Should not be needed, but reported to */
    while (ang > 180) ang -= 360;	/* avoid a bug in some libgd versions    */
    png_state.angle = ang;
    return TRUE;
}

TERM_PUBLIC int
PNG_justify_text(enum JUSTIFY mode)
{
#ifdef HAVE_GD_TTF
    png_state.justify = mode;
    return TRUE;
#else
    return null_justify_text(mode);
#endif
}

TERM_PUBLIC void
PNG_point(unsigned int x, unsigned int y, int number)
{
    int save_color = png_state.color;

    if (number < 0) { /* Dot */
	gdImageSetPixel(png_state.image, x, Y(y), png_state.color);
	return;
    }
    /* Use current linewidth to draw the point symbol */
    if (png_state.linewidth > 1) {
	/* EAM - Implement linewidth by using a brush */
	int lw   = png_state.linewidth;
	PNG_init_brush(lw);
	gdImageSetBrush(png_state.image, PNG_brush[lw]->im);
	png_state.color = gdBrushed;
    }

    y = Y(y);

    switch (number % 13) {
    case 0: /* plus */
    default:
	PNG_PointPlus(x, y);
	break;
    case 1: /* X */
	PNG_PointX(x, y);
	break;
    case 2: /* star */
	PNG_PointPlus(x, y);
	PNG_PointX(x, y);
	break;
    case 3: /* box */
	gdImageRectangle(png_state.image, x - PNG_ps, y - PNG_ps,
			 x + PNG_ps, y + PNG_ps, png_state.color);
	break;
    case 4: /* box                   filled */
	gdImageFilledRectangle(png_state.image, x - PNG_ps, y - PNG_ps,
			       x + PNG_ps, y + PNG_ps, png_state.color);
	break;
    case 5: /* circle */
	gdImageArc(png_state.image, x, y, 2 * PNG_ps, 2 * PNG_ps,
		   0, 360, png_state.color);
	break;
    case 6: /* circle (disk)         filled */
	gdImageFilledArc(png_state.image, x, y, 2 * PNG_ps, 2 * PNG_ps,
		   0, 360, png_state.color, gdArc);
	break;
    case 7: /* triangle */
	PNG_Triangle(x, y, 1, gp_gdImagePolygon);
	break;
    case 8: /* triangle              filled */
	PNG_Triangle(x, y, 1, gp_gdImageFilledPolygon);
	break;
    case 9: /* upside down triangle */
	PNG_Triangle(x, y, -1, gp_gdImagePolygon);
	break;
    case 10: /* upside down triangle  filled */
	PNG_Triangle(x, y, -1, gp_gdImageFilledPolygon);
	break;
    case 11: /* diamond */
	PNG_Diamond(x, y, gp_gdImagePolygon);
	break;
    case 12: /* diamond               filled */
	PNG_Diamond(x, y, gp_gdImageFilledPolygon);
	break;
    }

    png_state.color = save_color;
}

TERM_PUBLIC int
PNG_set_font(const char *fontname)
{
    int  sep;
    int  size;
    gdFontPtr font = png_state.default_font;
    char *name = gp_strdup(fontname);

    sep = strcspn(fontname,",");
    strncpy(name,fontname,sep);
    name[sep] = '\0';
    if ((sscanf(&(fontname[sep+1]),"%d",&size) < 1)
    || !(size > 0))
	size = png_state.default_ttfsize;

    if (!strcmp(name,"small"))
	font = gdFontGetSmall();
    else if (!strcmp(name,"medium"))
	font = gdFontGetMediumBold();
    else if (!strcmp(name,"large"))
	font = gdFontGetLarge();
    else if (!strcmp(name,"giant"))
	font = gdFontGetGiant();
    else if (!strcmp(name,"tiny"))
	font = gdFontGetTiny();
    else if (*name) {
	/* New ttf font */
	free(png_state.ttffont);
	png_state.ttffont = gp_strdup(name);
	png_state.ttfsize = size;
    } else {
	/* Restore initial default font */
	free(png_state.ttffont);
	png_state.ttffont = gp_strdup(png_state.default_ttffont);
	png_state.ttfsize = size;
    }
    free(name);

    png_state.font  = font;
    png_state.charw = font->w;
    png_state.charh = font->h;

/* EAM 9-Feb-2003 Make new font size visible to higher level routines like write_multiline */
    term->h_char = font->w;
    term->v_char = font->h;
#ifdef HAVE_GD_TTF
    /* Find approximate character width and height of selected TTF font */
    if (png_state.ttffont) {
	int brect[8];
	char *err;
        /* First try the old GDFONTPATH mechanism for locating fonts */
	(void)gdUseFontConfig(0);
	err = gdImageStringFT(NULL, &brect[0], 0,
		png_state.ttffont, (double)png_state.ttfsize*png_state.fontscale,
		0.0, 0, 0, "f00000000g");
	/* If that didn't work, try again using fontconfig mechanism */
	if (err && gdUseFontConfig(1)) {
	    FPRINTF((stderr,"DEBUG1: gd.trm:3: gdUseFontConfig(1) (%s)\n",
		    png_state.ttffont));
	    err = gdImageStringFT(NULL, &brect[0], 0,
		png_state.ttffont, 
		(double)png_state.default_ttfsize*png_state.fontscale,
		0.0, 0, 0, "f00000000g");
	}
	if (!err) {
	    term->h_char = .11 * (float)(brect[2] - brect[0]) + 0.5;
	    term->v_char = 1.1 * (float)(brect[1] - brect[7]) + 0.5;
	}
    }
#endif

    return TRUE;
}

TERM_PUBLIC void
PNG_pointsize(double ptsize)
{
    if (ptsize < 0)
	ptsize = 1;
    PNG_ps = (int)(((double)PNG_POINT_SCALE * ptsize) + 0.5);
}

/*
 * Ethan A Merritt November 2003
 *	- Support for enhanced text mode
 * BUGS:
 *	- placement of overprinted characters is not correct;
 *	  the overprinted text (pass 2) should be centered, not left-justified
 * PROBLEMS:
 *	- the Symbol font encoding didn't work in libgd until 2.0.21
 * 	- Placement of superscripts and subscripts relies on information
 * 	  in the font description that is not always reliable
 *	- the TTF character encoding for non-keyboard characters does
 *	  not always match the PostScript standard.
 *	- Spacing of rotated text is incorrect; I believe this is a due
 *	  to a problem in the text rotation code (aspect ratio??).
 */

static TBOOLEAN ENHgd_opened_string;

/* used in determining height of processed text */
static float ENHgd_base;

/* use these so that we don't over-write the current font settings in png_state */
static double  ENHgd_fontsize;
static char   *ENHgd_font;

static int ENHgd_overprint = 0;
static TBOOLEAN ENHgd_widthflag = TRUE;
static unsigned int ENHgd_xsave, ENHgd_ysave;

TERM_PUBLIC void
ENHGD_OPEN(
    char *fontname,
    double fontsize, double base,
    TBOOLEAN widthflag,
    TBOOLEAN showflag,
    int overprint)
{
    /* If the overprint code requests a save or restore, that's all we do */
    if (overprint == 3) {
	ENHgd_xsave = png_state.x;
	ENHgd_ysave = png_state.y;
	return;
    } else if (overprint == 4) {
	PNG_move(ENHgd_xsave, ENHgd_ysave);
	return;
    }

    if (!ENHgd_opened_string) {
	ENHgd_opened_string = TRUE;
	enhanced_cur_text = &enhanced_text[0];
	ENHgd_font = fontname;
	ENHgd_fontsize = fontsize;
	ENHgd_base = base;
	ENHgd_show = showflag;
	ENHgd_overprint = overprint;
	ENHgd_widthflag = widthflag;
    }
}

/* Write a string fragment and update the current position */
TERM_PUBLIC void
ENHGD_FLUSH()
{
    int brect[8]; char *err;
    unsigned int x, y;
    char *fragment = enhanced_text;

    if (!ENHgd_opened_string)
	return;

    ENHgd_opened_string = FALSE;
    *enhanced_cur_text = '\0';

    /* Mar 2011 - added to handle SJIS/UTF8 conversion */
    if (contains8bit(fragment)) {
	gd_iconv(&fragment);
    }

    x = png_state.x;
    y = png_state.y;
    x -= sin((double)png_state.angle * M_PI_2/90.) * ENHgd_base;
    y += cos((double)png_state.angle * M_PI_2/90.) * ENHgd_base;
    x += sin((double)png_state.angle * M_PI_2/90.) * (double)png_state.charh/4.;
    y -= cos((double)png_state.angle * M_PI_2/90.) * (double)png_state.charh/4.;

    /* First try the old GDFONTPATH mechanism for locating fonts */
    (void)gdUseFontConfig(0);
#ifdef gdFTEX_Adobe_Custom
    /* libgd defaults to UTF-8 encodings. We have limited options for	*/
    /* over-riding this, but we can try					*/
    if (encoding != S_ENC_UTF8 && ENHgd_font && !strcmp(ENHgd_font,"Symbol")) {
	PNG_FONT_INFO.flags |= gdFTEX_CHARMAP;
	PNG_FONT_INFO.charmap = gdFTEX_Adobe_Custom;
    } else {
	PNG_FONT_INFO.flags &= ~gdFTEX_CHARMAP;
	PNG_FONT_INFO.charmap = 0;   /* gdFTEX_Adobe_Custom */
    }
    err = gdImageStringFTEx(
		(ENHgd_show && !ENHgd_sizeonly) ? png_state.image : NULL,
		brect, png_state.color,
		ENHgd_font, ENHgd_fontsize,
		(double)png_state.angle * M_PI_2/90.,
		x, Y(y), fragment, &PNG_FONT_INFO);
    if (err && gdUseFontConfig(1)) {
	err = gdImageStringFTEx(
		(ENHgd_show && !ENHgd_sizeonly) ? png_state.image : NULL,
		brect, png_state.color,
		ENHgd_font, ENHgd_fontsize,
		(double)png_state.angle * M_PI_2/90.,
		x, Y(y), fragment, &PNG_FONT_INFO);
    }
#else
    err = gdImageStringFT(
		(ENHgd_show && !ENHgd_sizeonly) ? png_state.image : NULL,
		brect, png_state.color,
		ENHgd_font, ENHgd_fontsize,
		(double)png_state.angle * M_PI_2/90.,
		x, Y(y), fragment);
    if (err && gdUseFontConfig(1)) {
	err = gdImageStringFT(
		(ENHgd_show && !ENHgd_sizeonly) ? png_state.image : NULL,
		brect, png_state.color,
		ENHgd_font, ENHgd_fontsize,
		(double)png_state.angle * M_PI_2/90.,
		x, Y(y), fragment);
    }
#endif
    if (err) 
	fprintf(stderr,"gdImageStringFT: %s while printing string %s with font %s\n",
	    err,enhanced_text,ENHgd_font);

#ifdef EAM_BOXED_TEXT
    if (!ENHgd_sizeonly) {
	int xmax = GPMAX(brect[2],brect[6]);
	int xmin = GPMIN(brect[0],brect[4]);
	int ymax = GPMIN(brect[1],brect[3]);
	int ymin = GPMAX(brect[5],brect[7]);
	if (xmin < bounding_box[0]) bounding_box[0] = xmin;
	if (xmax > bounding_box[2]) bounding_box[2] = xmax;
	if (ymin < bounding_box[1]) bounding_box[1] = ymin;
	if (ymax > bounding_box[3]) bounding_box[3] = ymax;
    }
#endif

    if (ENHgd_overprint == 1) {
	png_state.x += ((brect[2] - brect[0]))/2;
	png_state.y -= (brect[3] - brect[1]);
    } else if (ENHgd_widthflag) {
	png_state.x += (brect[2] - brect[0]);
	png_state.y -= (brect[3] - brect[1]);
    }
}

TERM_PUBLIC void
ENHGD_put_text(unsigned int x, unsigned int y, const char *str)
{
    char *original_string = (char *)str;

    if (ignore_enhanced_text || !png_state.ttffont) {
	PNG_put_text(x,y,str);
	return;
    }

    if (!strlen(str))
	return;

    /* if there are no magic characters, we should just be able
     * punt the string to PNG_put_text()
     */
    if (!strpbrk(str, "{}^_@&~")) {
	/* FIXME: do something to ensure default font is selected */
	PNG_put_text(x,y,str);
	return;
    }

    PNG_move(x,y);

    /* set up the global variables needed by enhanced_recursion() */
    enhanced_fontscale = png_state.fontscale;
    strncpy(enhanced_escape_format,"&#x%2.2x;",sizeof(enhanced_escape_format));

    ENHgd_opened_string = FALSE;
    ENHgd_show = TRUE;
    ENHgd_overprint = 0;

    /* EAM - post.trm wasn't doing this, but how else do they get initialized? */
	ENHgd_font = png_state.ttffont;
	ENHgd_fontsize = png_state.ttfsize;

    /* EAM - Software text justification requires two passes */
    if (png_state.justify == RIGHT || png_state.justify == CENTRE)
	ENHgd_sizeonly = TRUE;

    /* Set the recursion going. We say to keep going until a
     * closing brace, but we don't really expect to find one.
     * If the return value is not the nul-terminator of the
     * string, that can only mean that we did find an unmatched
     * closing brace in the string. We increment past it (else
     * we get stuck in an infinite loop) and try again.
     */
    while (*(str = enhanced_recursion((char *)str, TRUE,
			ENHgd_font, ENHgd_fontsize * png_state.fontscale,
			0.0, TRUE, TRUE, 0))) {
	(term->enhanced_flush)();

	/* I think we can only get here if *str == '}' */
	    enh_err_check(str);

	if (!*++str)
	    break; /* end of string */

	/* else carry on and process the rest of the string */
    }

    /* We can do text justification by running the entire top level string */
    /* through 2 times, with the ENHgd_sizeonly flag set the first time.   */
    /* After seeing where the final position is, we then offset the start  */
    /* point accordingly and run it again without the flag set.            */
    if (png_state.justify == RIGHT || png_state.justify == CENTRE) {
	int justification = png_state.justify;
	int x_offset = png_state.x - x;
	int y_offset = 0;

	if (png_state.angle != 0)
	    y_offset = png_state.y - y;
	png_state.justify = LEFT;
	ENHgd_sizeonly = FALSE;

	if (justification == RIGHT) {
	    ENHGD_put_text(x - x_offset, y - y_offset, original_string);
	} else if (justification == CENTRE) {
	    ENHGD_put_text(x - x_offset/2, y - y_offset/2, original_string);
	}
	png_state.justify = justification;
    }

}

#ifdef EAM_BOXED_TEXT
TERM_PUBLIC void
ENHGD_boxed_text(unsigned int x, unsigned int y, int option)
{
    switch (option) {
    case TEXTBOX_INIT:
	/* Initialize bounding box for this text string */
	bounding_box[0] = bounding_box[2] = x;
	bounding_box[1] = bounding_box[3] = Y(y);
	break;
    case TEXTBOX_OUTLINE:
	/* Stroke the outline of the bounding box for previous text */
	gdImageLine(png_state.image,
		bounding_box[0]-bounding_xmargin, bounding_box[1]-bounding_ymargin,
	 	bounding_box[0]-bounding_xmargin, bounding_box[3]+bounding_ymargin,
		png_state.color);
	gdImageLine(png_state.image,
		bounding_box[0]-bounding_xmargin, bounding_box[3]+bounding_ymargin,
		bounding_box[2]+bounding_xmargin, bounding_box[3]+bounding_ymargin,
		png_state.color);
	gdImageLine(png_state.image,
		bounding_box[2]+bounding_xmargin, bounding_box[3]+bounding_ymargin,
		bounding_box[2]+bounding_xmargin, bounding_box[1]-bounding_ymargin,
		png_state.color);
	gdImageLine(png_state.image,
		bounding_box[2]+bounding_xmargin, bounding_box[1]-bounding_ymargin,
		bounding_box[0]-bounding_xmargin, bounding_box[1]-bounding_ymargin,
		png_state.color);
	break;
    case TEXTBOX_BACKGROUNDFILL:
	/* Fill the box with background color. FIXME - other colors? */
	gdImageFilledRectangle(png_state.image,
		bounding_box[0] - bounding_xmargin,
		bounding_box[1] - bounding_ymargin,
		bounding_box[2] + bounding_xmargin,
		bounding_box[3] + bounding_ymargin,
		png_state.color_table[0]);
	break;
    case TEXTBOX_MARGINS:
	/* Change the text margins */
	bounding_xmargin = GD_TEXTBOX_MARGIN * (double)x / 100.;
	bounding_ymargin = GD_TEXTBOX_MARGIN * (double)y / 100.;
	break;
    default:
    	break;
    }
}
#endif



#undef gdfont

TERM_PUBLIC void
PNG_image (unsigned int M, unsigned int N, coordval * image, gpiPoint * corner, t_imagecolor color_mode)
{
    int m, n, mout, nout;
    int x1,y1,x2,y2;
    int xclip1, xclip2, yclip1, yclip2;
    int pixel;
    gdImagePtr im;

    if (png_state.TrueColor) {
	im = gdImageCreateTrueColor(M, N);
	if (!im)
	    int_error(NO_CARET,"libgd: failed to create image structure");
    } else {
	im = gdImageCreate(M, N);
	if (!im)
	    int_error(NO_CARET,"libgd: failed to create image structure");
	gdImagePaletteCopy(im, png_state.image);
    }

    /* Set clipping bound for area into which we will copy */
    xclip1 = GPMIN(corner[2].x, corner[3].x);
    xclip2 = GPMAX(corner[2].x, corner[3].x);
    yclip1 = GPMIN(Y(corner[2].y), Y(corner[3].y));
    yclip2 = GPMAX(Y(corner[2].y), Y(corner[3].y));
    gdImageGetClip(png_state.image, &x1, &y1, &x2, &y2);
    gdImageSetClip(png_state.image, xclip1, yclip1, xclip2, yclip2);

    /* Initialize image area with current contents of plot. */
    mout = abs( (int)corner[1].x - (int)corner[0].x );
    nout = abs( (int)corner[1].y - (int)corner[0].y );

    if (color_mode == IC_RGBA) {
	/* RGB + Alpha channel
	 * Resize explicitly in a loop rather than calling a library
	 * routine in order not to apply the alpha correction more than
	 * once when building up any given output pixel.
	 */
	for (n=0; n<nout; n++) {
	for (m=0; m<mout; m++) {
	    rgb_color rgb1;
	    rgb255_color rgb255;
	    int alpha;
	    int msrc = (m*(long)(M-1))/(mout-1);
	    int nsrc = (n*(long)(N-1))/(nout-1);
	    coordval *cval = image + 4*(M*nsrc + msrc);
	    rgb1.r = *cval++;
	    rgb1.g = *cval++;
	    rgb1.b = *cval++;
	    alpha  = *cval++;
	    alpha  = 127 - (alpha>>1);	/* input is [0:255] but gd wants [127:0] */
	    rgb255_from_rgb1( rgb1, &rgb255 );
	    pixel = gdImageColorResolveAlpha( png_state.image,
		(int)rgb255.r, (int)rgb255.g, (int)rgb255.b, alpha);
	    gdImageSetPixel( png_state.image, m + corner[0].x, n + Y(corner[0].y), pixel );
	}
	}

    } else if (color_mode == IC_RGB) {
	/* TrueColor 24-bit color mode */
	for (n=0; n<N; n++) {
	for (m=0; m<M; m++) {
	    rgb_color rgb1;
	    rgb255_color rgb255;
	    rgb1.r = *image++;
	    rgb1.g = *image++;
	    rgb1.b = *image++;
	    rgb255_from_rgb1( rgb1, &rgb255 );
	    pixel = gdImageColorResolve( im, 
		(int)rgb255.r, (int)rgb255.g, (int)rgb255.b );
	    gdImageSetPixel( im, m, n, pixel );
	}
	}

    } else if (color_mode == IC_PALETTE) {
	/* Palette color lookup from gray value */
	for (n=0; n<N; n++) {
	for (m=0; m<M; m++) {
	    rgb255_color rgb;
	    if (isnan(*image)) {
		/* Transparent would be even better */
		pixel = png_state.color_table[0];
		image++;
	    } else {
		rgb255maxcolors_from_gray( *image++, &rgb );
		pixel = gdImageColorResolve( im,
		    (int)rgb.r, (int)rgb.g, (int)rgb.b );
	    }
	    gdImageSetPixel( im, m, n, pixel );
	}
	}
    }

    /* Copy and resize onto requested region of plot */
    if (color_mode != IC_RGBA)
	gdImageCopyResized(png_state.image, im,
		(corner[0].x), Y(corner[0].y),	/* Destination X, Y */
		0, 0, 				/* Source X, Y */
		mout, nout,			/* Destination Width, Height */
		M, N				/* Source Width, Height */
		);
    gdImageDestroy(im);

    /* Restore previous clipping, if any */
    gdImageSetClip(png_state.image, x1, y1, x2, y2);

}


/* Mar 2011 - shige takeno
 * libgd can be built to prefer UTF-8 or SJIS encoding for Japanese.
 * If it wants SJIS and we are currently in UTF8, convert.
 * If it wants UTF8 and we are currently in SJIS, convert.
 */
static void
gd_iconv(char **string)
{
#ifdef HAVE_ICONV
    size_t len1 = strlen(*string)+1;
    size_t len2;
    iconv_t cd;
    char *stmp;

    /* We will return this to the caller and free it next time */
    static char *iconv_string = NULL;
    free(iconv_string);
    iconv_string = NULL;

#ifdef JIS_GDLIB
    if (encoding == S_ENC_UTF8) { /* UTF-8 -> Shift_JIS by iconv */
	len2 = len1;
	iconv_string = gp_alloc(len2, "iconv string");
	stmp = iconv_string;
	if ((cd = iconv_open("Shift_JIS", "UTF-8")) == (iconv_t)-1)
	  int_warn(NO_CARET, "iconv_open failed");
	else {
	    if (iconv(cd, (void *)string, &len1, &stmp, &len2) == (size_t)-1)
		int_warn(NO_CARET, "iconv failed");
	    else
		*string = iconv_string;
	    iconv_close(cd);
	}
    }
#else /* ! JIS_GDLIB */
    if (encoding == S_ENC_SJIS) { /* Shift_JIS -> UTF-8 by iconv */
	len2 = len1*3/2+2;
	iconv_string = gp_alloc(len2, "iconv string");
	stmp = iconv_string;
	if ((cd = iconv_open("UTF-8", "Shift_JIS")) == (iconv_t)-1)
	  int_warn(NO_CARET, "iconv_open failed");
	else {
	    if (iconv(cd, (void *)string, &len1, &stmp, &len2) == (size_t)-1)
		int_warn(NO_CARET, "iconv failed");
	    else
		*string = iconv_string;
	    iconv_close(cd);
	}
    }
#endif /* JIS_GDLIB */
#else /* ! HAVE_ICONV */
#ifdef JIS_GDLIB
    if (encoding == S_ENC_UTF8)
	int_warn(NO_CARET,
		 "This gdlib supports Shift_JIS encoding, but not UTF-8.");
#else /* ! JIS_GDLIB */
    if (encoding == S_ENC_SJIS) /* Shift_JIS -> UTF-8 */
	int_warn(NO_CARET,
		 "This gdlib supports UTF-8 encoding, but not Shift_JIS.");
#endif  /* JIS_GDLIB */
#endif /* HAVE_ICONV */
}

#undef MAXLINEWIDTH
#undef Y

#endif /* TERM_BODY */
#ifdef TERM_TABLE

TERM_TABLE_START(png_driver)
    "png", "PNG images using libgd and TrueType fonts",
    GREG_XMAX, GREG_YMAX, PNG_VCHAR, PNG_HCHAR,
    PNG_TICSIZE, PNG_TICSIZE, PNG_options, PNG_init, PNG_reset,
    PNG_text, null_scale, PNG_graphics, PNG_move, PNG_vector,
    PNG_linetype, PNG_put_text, PNG_text_angle,
    PNG_justify_text, PNG_point, do_arrow, PNG_set_font,
    PNG_pointsize,
    TERM_CAN_MULTIPLOT|TERM_BINARY|TERM_LINEWIDTH|TERM_FONTSCALE, /* TERM_ALPHA_CHANNEL only if truecolor */
    0 /*suspend*/, 0 /*resume*/,
    PNG_boxfill /*EAM - fillbox*/,
    PNG_linewidth /*EAM - linewidth*/
#ifdef USE_MOUSE
    , 0, 0, 0, 0, 0 /* no mouse support */
#endif
    , PNG_make_palette,
    0, /* previous_palette() ... no, single array of 256 colours for PNG */
    PNG_set_color,
    PNG_filled_polygon
    , PNG_image
    , ENHGD_OPEN, ENHGD_FLUSH, do_enh_writec
    , NULL		/* layering */
    , NULL		/* path */
    , 0.0		/* tscale */
    , NULL		/* hypertext */
#ifdef EAM_BOXED_TEXT
    , ENHGD_boxed_text
#endif
TERM_TABLE_END(png_driver)

#undef LAST_TERM
#define LAST_TERM png_driver

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

#ifndef JPEG_HELP_ONLY
#ifdef TERM_HELP
START_HELP(png)
"1 png",
"?commands set terminal png",
"?set terminal png",
"?set term png",
"?terminal png",
"?term png",
"?png",
" Syntax:",
"       set terminal png ",
"              {{no}enhanced}",
"              {{no}transparent} {{no}interlace}",
"              {{no}truecolor} {rounded|butt}",
"              {linewidth <lw>} {dashlength <dl>}",
"              {tiny | small | medium | large | giant}",
"              {font \"<face> {,<pointsize>}\"} {fontscale <scale>}",
"              {size <x>,<y>} {{no}crop}",
"              {background <rgb_color>}",
"",
" PNG, JPEG and GIF images are created using the external library libgd.",
" PNG plots may be viewed interactively by piping the output to the",
" 'display' program from the ImageMagick package as follows:",
"                set term png",
"                set output '| display png:-'",
" You can view the output from successive plot commands interactively by typing",
" <space> in the display window.  To save the current plot to a file,",
" left click in the display window and choose `save`.",
"",
" `transparent` instructs the driver to make the background color transparent.",
" Default is `notransparent`.",
"",
" `interlace` instructs the driver to generate interlaced PNGs.",
" Default is `nointerlace`.",
"",
" The `linewidth` and `dashlength` options are scaling factors that affect all",
" lines drawn, i.e. they are multiplied by values requested in various drawing",
" commands.",
"",
" By default output png images use 256 indexed colors. The `truecolor` option",
" instead creates TrueColor images with 24 bits of color information per pixel.",
" Transparent fill styles require the `truecolor` option. See `fillstyle`.",
" A transparent background is possible in either indexed or TrueColor images.",
"",
" `butt` instructs the driver to use a line drawing method that does",
" not overshoot the desired end point of a line.  This setting is only",
" applicable for line widths greater than 1.  This setting is most useful when",
" drawing horizontal or vertical lines.  Default is `rounded`.",
"",
" The details of font selection are complicated.",
" Two equivalent simple examples are given below:",
"      set term png font arial 11",
"      set term png font \"arial,11\"",
" For more information please see the separate section under `fonts`.",
"",
" The output plot size <x,y> is given in pixels---it defaults to 640x480.",
" Please see additional information under `canvas` and `set size`.",
" Blank space at the edges of the finished plot may be trimmed using the `crop`",
" option, resulting in a smaller final image size. Default is `nocrop`.",
"",
"2 examples",
"?set term png examples",
"       set terminal png medium size 640,480 background '#ffffff'",
"",
" Use the medium size built-in non-scaleable, non-rotatable font.",
" Use white (24-bit RGB in hexadecimal) for the non-transparent background.",
"",
"       set terminal png font arial 14 size 800,600",
"",
" Searches for a scalable font with face name 'arial' and sets the font",
" size to 14pt.  Please see `fonts` for details of how the font search",
" is done.",
"",
"       set terminal png transparent truecolor enhanced",
"",
" Use 24 bits of color information per pixel, with a transparent background.",
" Use the `enhanced text` mode to control the layout of strings to be printed.",
""
END_HELP(png)
#endif /* TERM_HELP */
#endif /* JPEG_HELP_ONLY */

/*
 * JPEG support comes almost for free.
 * We just piggy-back on the PNG routines, since they both go via libgd
 */
#ifdef HAVE_GD_JPEG

#ifdef TERM_REGISTER
register_term(jpeg)
#endif

#ifdef TERM_PROTO
TERM_PUBLIC void JPEG_text __PROTO((void));
#define GOT_NEXT_PROTO
#endif

#ifndef TERM_PROTO_ONLY

#ifdef TERM_BODY

#include <gd.h>
/*
 * All functions except the final write to file
 * are actually performed by the PNG driver code
 */
TERM_PUBLIC void
JPEG_text()
{
int quality = 90;

    image_do_crop();
    if (png_state.flags & PNG_USE_INTERLACE)
	gdImageInterlace(png_state.image, 1);
    gdImageJpeg(png_state.image, gpoutfile, quality);
    gdImageDestroy(png_state.image);
}

#endif /* TERM_BODY */

#ifdef TERM_TABLE

TERM_TABLE_START(jpeg_driver)
    "jpeg", "JPEG images using libgd and TrueType fonts",
    GREG_XMAX, GREG_YMAX, PNG_VCHAR, PNG_HCHAR,
    PNG_TICSIZE, PNG_TICSIZE, PNG_options, PNG_init, PNG_reset,
    JPEG_text, null_scale, PNG_graphics, PNG_move, PNG_vector,
    PNG_linetype, PNG_put_text, PNG_text_angle,
    PNG_justify_text, PNG_point, do_arrow, PNG_set_font,
    PNG_pointsize,
    TERM_CAN_MULTIPLOT|TERM_BINARY|TERM_ALPHA_CHANNEL|TERM_LINEWIDTH|TERM_FONTSCALE,
    0 /*suspend*/, 0 /*resume*/,
    PNG_boxfill /*EAM - fillbox*/,
    PNG_linewidth /*EAM - linewidth*/
#ifdef USE_MOUSE
    , 0, 0, 0, 0, 0 /* no mouse support */
#endif
    , PNG_make_palette,
    0, /* previous_palette() ... no, single array of 256 colours for PNG */
    PNG_set_color,
    PNG_filled_polygon
    , PNG_image
    , ENHGD_OPEN, ENHGD_FLUSH, do_enh_writec
    , NULL		/* layering */
    , NULL		/* path */
    , 0.0		/* tscale */
    , NULL		/* hypertext */
#ifdef EAM_BOXED_TEXT
    , ENHGD_boxed_text
#endif
TERM_TABLE_END(jpeg_driver)

#undef LAST_TERM
#define LAST_TERM jpeg_driver

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

#ifdef TERM_HELP
START_HELP(jpeg)
"1 jpeg",
"?commands set terminal jpeg",
"?set terminal jpeg",
"?set term jpeg",
"?terminal jpeg",
"?term jpeg",
"?jpeg",
" Syntax:",
"       set terminal jpeg ",
"              {{no}enhanced}",
"              {{no}interlace}",
"              {linewidth <lw>} {dashlength <dl>} {rounded|butt}",
"              {tiny | small | medium | large | giant}",
"              {font \"<face> {,<pointsize>}\"} {fontscale <scale>}",
"              {size <x>,<y>} {{no}crop}",
"              {background <rgb_color>}",
"",
" PNG, JPEG and GIF images are created using the external library libgd.",
" In most cases, PNG is to be preferred for single plots, and GIF for",
" animations.  Both are loss-less image formats, and produce better image",
" quality than the lossy JPEG format. This is in particular noticeable",
" for solid color lines against a solid background, i.e. exactly the sort",
" of image typically created by gnuplot.",
"",
" The `interlace` option creates a progressive JPEG image.",
" Default is `nointerlace`.",
"",
" The `linewidth` and `dashlength` options are scaling factors that affect all",
" lines drawn, i.e. they are multiplied by values requested in various drawing",
" commands.",
"",
" `butt` instructs the driver to use a line drawing method that does",
" not overshoot the desired end point of a line.  This setting is only",
" applicable for line widths greater than 1.  This setting is most useful when",
" drawing horizontal or vertical lines.  Default is `rounded`.",
"",
" The details of font selection are complicated.",
" Two equivalent simple examples are given below:",
"      set term jpeg font arial 11",
"      set term jpeg font \"arial,11\"",
" For more information please see the separate section under `fonts`.",
"",
" The output plot size <x,y> is given in pixels---it defaults to 640x480.",
" Please see additional information under `canvas` and `set size`.",
" Blank space at the edges of the finished plot may be trimmed using the `crop`",
" option, resulting in a smaller final image size. Default is `nocrop`.",
""
END_HELP(jpeg)
#endif /* TERM_HELP */
#endif /* HAVE_GD_JPEG */

#ifdef HAVE_GD_GIF
/*
 * GIF support comes almost for free.
 * We just piggy-back on the PNG routines, since they both go via libgd.
 * Required libgd version is 2.0.28 or newer.
 */
#ifdef HAVE_GD_GIF

#ifdef TERM_REGISTER
register_term(gif)
#endif

#ifdef TERM_PROTO
TERM_PUBLIC void GIF_text __PROTO((void));
#define GOT_NEXT_PROTO
#endif

#ifndef TERM_PROTO_ONLY

#ifdef TERM_BODY

#include <gd.h>
/*
 * All functions except the final write to file
 * are actually performed by the PNG driver code
 */
TERM_PUBLIC void
GIF_text()
{
    image_do_crop();

#ifdef GIF_ANIMATION
    if (png_state.animate) {
	/* Note - using a global colormap saves space, but it breaks	*/
	/* if later frames add new colors to the palette.		*/
	if (png_state.frame_count == 0) {
	    gdImageGifAnimBegin(png_state.image, gpoutfile, 
		1, /* Load Global Colormap even if it isn't used */ 
		png_state.loop_count );
	}
	gdImageGifAnimAdd(png_state.image, gpoutfile,
	    png_state.frame_optimization ? 0  /* use global map  */
	                                 : 1, /* use private map */
	    0, 0 /* No offset */,
	    png_state.frame_delay,
	    (png_state.flags & PNG_USE_TRANSPARENT)
			? gdDisposalRestorePrevious 
			: gdDisposalNone, 
	    (png_state.frame_optimization && !(png_state.flags & PNG_USE_TRANSPARENT))
	    ? png_state.previous_image : NULL);
	png_state.frame_count++;
	if (png_state.previous_image)
	    gdImageDestroy(png_state.previous_image);
	png_state.previous_image = png_state.image;
	return;
    }
#endif

    gdImageGif(png_state.image, gpoutfile);
    gdImageDestroy(png_state.image);
}

#endif /* TERM_BODY */

#ifdef TERM_TABLE

TERM_TABLE_START(gif_driver)
    "gif", "GIF images using libgd and TrueType fonts",
    GREG_XMAX, GREG_YMAX, PNG_VCHAR, PNG_HCHAR,
    PNG_TICSIZE, PNG_TICSIZE, PNG_options, PNG_init, PNG_reset,
    GIF_text, null_scale, PNG_graphics, PNG_move, PNG_vector,
    PNG_linetype, PNG_put_text, PNG_text_angle,
    PNG_justify_text, PNG_point, do_arrow, PNG_set_font,
    PNG_pointsize,
    TERM_CAN_MULTIPLOT|TERM_BINARY|TERM_LINEWIDTH|TERM_FONTSCALE,
    0 /*suspend*/, 0 /*resume*/,
    PNG_boxfill /*EAM - fillbox*/,
    PNG_linewidth /*EAM - linewidth*/
#ifdef USE_MOUSE
    , 0, 0, 0, 0, 0 /* no mouse support */
#endif
    , PNG_make_palette,
    0, /* previous_palette() ... no, single array of 256 colours for PNG */
    PNG_set_color,
    PNG_filled_polygon
    , PNG_image
    , ENHGD_OPEN, ENHGD_FLUSH, do_enh_writec
    , NULL		/* layering */
    , NULL		/* path */
    , 0.0		/* tscale */
    , NULL		/* hypertext */
#ifdef EAM_BOXED_TEXT
    , ENHGD_boxed_text
#endif
TERM_TABLE_END(gif_driver)

#undef LAST_TERM
#define LAST_TERM gif_driver

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


#ifdef TERM_HELP
START_HELP(gif)
"1 gif",
"?commands set terminal gif",
"?set terminal gif",
"?set term gif",
"?terminal gif",
"?term gif",
"?gif",
" Syntax:",
"       set terminal gif ",
"              {{no}enhanced}",
"              {{no}transparent} {rounded|butt}",
"              {linewidth <lw>} {dashlength <dl>}",
"              {tiny | small | medium | large | giant}",
"              {font \"<face> {,<pointsize>}\"} {fontscale <scale>}",
"              {size <x>,<y>} {{no}crop}",
"              {animate {delay <d>} {loop <n>} {{no}optimize}}",
"              {background <rgb_color>}",
"",
" PNG, JPEG and GIF images are created using the external library libgd.",
" GIF plots may be viewed interactively by piping the output to the",
" 'display' program from the ImageMagick package as follows:",
"                set term gif",
"                set output '| display gif:-'",
" You can view the output from successive plot commands interactively by typing",
" <space> in the display window.  To save the current plot to a file,",
" left click in the display window and choose `save`.",
"",
" `transparent` instructs the driver to make the background color transparent.",
" Default is `notransparent`.",
"",
" The `linewidth` and `dashlength` options are scaling factors that affect all",
" lines drawn, i.e. they are multiplied by values requested in various drawing",
" commands.",
"",
" `butt` instructs the driver to use a line drawing method that does",
" not overshoot the desired end point of a line.  This setting is only",
" applicable for line widths greater than 1.  This setting is most useful when",
" drawing horizontal or vertical lines.  Default is `rounded`.",
"",
" The details of font selection are complicated.",
" Two equivalent simple examples are given below:",
"      set term gif font arial 11",
"      set term gif font \"arial,11\"",
" For more information please see the separate section under `fonts`.",
"",
" The `animate` option is available only if your local gd library supports",
" the creation of animated gifs. The default delay between display of",
" successive images may be specified in units of 1/100 second (default 5).",
" The actual delay may vary depending on the program used as a viewer.",
" Number of animation loops can be specified, default 0 means infinity.",
" An animation sequence is terminated by the next `set output` or `set term`",
" command.  The `optimize` option has two effects on the animation.",
"",
" 1) A single color map is used for the entire animation. This requires",
" that all colors used in any frame of the animation are already",
" defined in the first frame.",
"",
" 2) If possible, only the portions of a frame that differ from the",
" previous frame are stored in the animation file.  This space saving",
" may not be possible if the animation uses transparency.",
"",
" Both of these optimizations are intended to produce a smaller output file,",
" but the decrease in size is probably only significant for long animations",
" or very small frame sizes.",
" The `nooptimize` option turns off both of the effects just described.",
" Each frame is stored in its entirety along with a private color map.",
" Note that it is possible to post-process a non-optimized animation",
" using external utilities, and this post-processing can yield a smaller",
" file than gnuplot's internal optimization mode.",
" The default is `nooptimize`.",
"",
" The output plot size <x,y> is given in pixels---it defaults to 640x480.",
" Please see additional information under `canvas` and `set size`.",
" Blank space at the edges of the finished plot may be trimmed using the `crop`",
" option, resulting in a smaller final image size. Default is `nocrop`.",
"",
"2 examples",
"?set term gif examples",
"       set terminal gif medium size 640,480 background '#ffffff'",
"",
" Use the medium size built-in non-scaleable, non-rotatable font.",
" Use white (24 bit RGB in hexadecimal) for the non-transparent background.",
"",
"       set terminal gif font arial 14 enhanced",
"",
" Searches for a scalable font with face name 'arial' and sets the font",
" size to 14pt.  Please see `fonts` for details of how the font search",
" is done.  Because this is a scalable font, we can use enhanced text mode.",
"",
"       set term gif animate transparent opt delay 10 size 200,200",
"       load \"animate2.dem\"",
"",
" Open the gif terminal for creation of an animated gif file.  The individual",
" frames of the animation sequence are created by the script file animate2.dem",
" from the standard collection of demos.",
""
END_HELP(gif)
#endif /* TERM_HELP */
#endif /* HAVE_GD_GIF */
#endif