Blame view

site/jpgraph/gd_image.inc.php 83 KB
8ec98c9f   Guillaume   MAJ
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
  <?php
  //=======================================================================
  // File:        GD_IMAGE.INC.PHP
  // Description: PHP Graph Plotting library. Low level image drawing routines
  // Created:     2001-01-08, refactored 2008-03-29
  // Ver:         $Id: gd_image.inc.php 1922 2010-01-11 11:42:50Z ljp $
  //
  // Copyright (c) Asial Corporation. All rights reserved.
  //========================================================================
  
  require_once 'jpgraph_rgb.inc.php';
  require_once 'jpgraph_ttf.inc.php';
  require_once 'imageSmoothArc.php';
  require_once 'jpgraph_errhandler.inc.php';
  
  // Line styles
  define('LINESTYLE_SOLID',1);
  define('LINESTYLE_DOTTED',2);
  define('LINESTYLE_DASHED',3);
  define('LINESTYLE_LONGDASH',4);
  
  // The DEFAULT_GFORMAT sets the default graphic encoding format, i.e.
  // PNG, JPG or GIF depending on what is installed on the target system
  // in that order.
  if( !DEFINED("DEFAULT_GFORMAT") ) {
      define("DEFAULT_GFORMAT","auto");
  }
  
  //========================================================================
  // CLASS Image
  // Description: The very coor image drawing class that encapsulates all
  //              calls to the GD library
  //              Note: The class used by the library is the decendant
  //              class RotImage which extends the Image class with transparent
  //              rotation.
  //=========================================================================
  class Image {
      public $img=null;
      public $rgb=null;
      public $img_format;
      public $ttf=null;
      public $line_style=LINESTYLE_SOLID;
      public $current_color,$current_color_name;
      public $original_width=0, $original_height=0;
      public $plotwidth=0,$plotheight=0;
  
      // for __get, __set
      private $_left_margin=30,$_right_margin=30,$_top_margin=20,$_bottom_margin=30;
      //private $_plotwidth=0,$_plotheight=0;
      private $_width=0, $_height=0;
      private $_line_weight=1;
  
      protected $expired=true;
      protected $lastx=0, $lasty=0;
      protected $obs_list=array();
      protected $font_size=12,$font_family=FF_DEFAULT, $font_style=FS_NORMAL;
      protected $font_file='';
      protected $text_halign="left",$text_valign="bottom";
      protected $use_anti_aliasing=false;
      protected $quality=null;
      protected $colorstack=array(),$colorstackidx=0;
      protected $canvascolor = 'white' ;
      protected $langconv = null ;
      protected $iInterlace=false;
      protected $bbox_cache = array(); // STore the last found tetx bounding box
      protected $ff_font0;
      protected $ff_font0_bold;
      protected $ff_font1;
      protected $ff_font1_bold;
      protected $ff_font2;
      protected $ff_font2_bold;
  
  
      //---------------
      // CONSTRUCTOR
      function __construct($aWidth=0,$aHeight=0,$aFormat=DEFAULT_GFORMAT,$aSetAutoMargin=true) {
  
          $this->original_width  = $aWidth;
          $this->original_height = $aHeight;
          $this->CreateImgCanvas($aWidth, $aHeight);
  
          if( $aSetAutoMargin ) {
              $this->SetAutoMargin();
          }
  
          if( !$this->SetImgFormat($aFormat) ) {
              JpGraphError::RaiseL(25081,$aFormat);//("JpGraph: Selected graphic format is either not supported or unknown [$aFormat]");
          }
          $this->ttf = new TTF();
          $this->langconv = new LanguageConv();
  
          $this->ff_font0 =  imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT0.gdf");
          $this->ff_font1 =  imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT1.gdf");
          $this->ff_font2 =  imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT2.gdf");
          $this->ff_font1_bold =  imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT1-Bold.gdf");
          $this->ff_font2_bold =  imageloadfont(dirname(__FILE__) . "/fonts/FF_FONT2-Bold.gdf");
      }
  
      // Enable interlacing in images
      function SetInterlace($aFlg=true) {
          $this->iInterlace=$aFlg;
      }
  
      // Should we use anti-aliasing. Note: This really slows down graphics!
      function SetAntiAliasing($aFlg=true) {
          $this->use_anti_aliasing = $aFlg;
          if( function_exists('imageantialias') ) {
              imageantialias($this->img,$aFlg);
          }
          else {
              JpGraphError::RaiseL(25128);//('The function imageantialias() is not available in your PHP installation. Use the GD version that comes with PHP and not the standalone version.')
          }
      }
  
      function GetAntiAliasing() {
          return $this->use_anti_aliasing ;
      }
  
      function CreateRawCanvas($aWidth=0,$aHeight=0) {
  
          $aWidth  *= SUPERSAMPLING_SCALE;
          $aHeight *= SUPERSAMPLING_SCALE;
  
          if( $aWidth <= 1 || $aHeight <= 1 ) {
              JpGraphError::RaiseL(25082,$aWidth,$aHeight);//("Illegal sizes specified for width or height when creating an image, (width=$aWidth, height=$aHeight)");
          }
  
          $this->img = @imagecreatetruecolor($aWidth, $aHeight);
          if( $this->img < 1 ) {
              JpGraphError::RaiseL(25126);
              //die("Can't create truecolor image. Check that you really have GD2 library installed.");
          }
          $this->SetAlphaBlending();
  
          if( $this->iInterlace ) {
              imageinterlace($this->img,1);
          }
          if( $this->rgb != null ) {
              $this->rgb->img = $this->img ;
          }
          else {
              $this->rgb = new RGB($this->img);
          }
      }
  
      function CloneCanvasH() {
          $oldimage = $this->img;
          $this->CreateRawCanvas($this->width,$this->height);
          imagecopy($this->img,$oldimage,0,0,0,0,$this->width,$this->height);
          return $oldimage;
      }
  
      function CreateImgCanvas($aWidth=0,$aHeight=0) {
  
          $old = array($this->img,$this->width,$this->height);
  
          $aWidth = round($aWidth);
          $aHeight = round($aHeight);
  
          $this->width=$aWidth;
          $this->height=$aHeight;
  
  
          if( $aWidth==0 || $aHeight==0 ) {
              // We will set the final size later.
              // Note: The size must be specified before any other
              // img routines that stroke anything are called.
              $this->img = null;
              $this->rgb = null;
              return $old;
          }
  
          $this->CreateRawCanvas($aWidth,$aHeight);
          // Set canvas color (will also be the background color for a
          // a pallett image
          $this->SetColor($this->canvascolor);
          $this->FilledRectangle(0,0,$this->width-1,$this->height-1);
  
          return $old ;
      }
  
      function CopyCanvasH($aToHdl,$aFromHdl,$aToX,$aToY,$aFromX,$aFromY,$aWidth,$aHeight,$aw=-1,$ah=-1) {
          if( $aw === -1 ) {
              $aw = $aWidth;
              $ah = $aHeight;
              $f = 'imagecopyresized';
          }
          else {
              $f = 'imagecopyresampled';
          }
          $f($aToHdl,$aFromHdl,$aToX,$aToY,$aFromX,$aFromY, $aWidth,$aHeight,$aw,$ah);
      }
  
      function Copy($fromImg,$toX,$toY,$fromX,$fromY,$toWidth,$toHeight,$fromWidth=-1,$fromHeight=-1) {
          $this->CopyCanvasH($this->img,$fromImg,$toX,$toY,$fromX,$fromY,$toWidth,$toHeight,$fromWidth,$fromHeight);
      }
  
      function CopyMerge($fromImg,$toX,$toY,$fromX,$fromY,$toWidth,$toHeight,$fromWidth=-1,$fromHeight=-1,$aMix=100) {
          if( $aMix == 100 ) {
              $this->CopyCanvasH($this->img,$fromImg,
              $toX,$toY,$fromX,$fromY,$toWidth,$toHeight,$fromWidth,$fromHeight);
          }
          else {
              if( ($fromWidth  != -1 && ($fromWidth != $toWidth)) || ($fromHeight != -1 && ($fromHeight != $fromHeight)) ) {
                  // Create a new canvas that will hold the re-scaled original from image
                  if( $toWidth <= 1 || $toHeight <= 1 ) {
                      JpGraphError::RaiseL(25083);//('Illegal image size when copying image. Size for copied to image is 1 pixel or less.');
                  }
  
                  $tmpimg = @imagecreatetruecolor($toWidth, $toHeight);
  
                  if( $tmpimg < 1 ) {
                      JpGraphError::RaiseL(25084);//('Failed to create temporary GD canvas. Out of memory ?');
                  }
                  $this->CopyCanvasH($tmpimg,$fromImg,0,0,0,0,
                  $toWidth,$toHeight,$fromWidth,$fromHeight);
                  $fromImg = $tmpimg;
              }
              imagecopymerge($this->img,$fromImg,$toX,$toY,$fromX,$fromY,$toWidth,$toHeight,$aMix);
          }
      }
  
      static function GetWidth($aImg) {
          return imagesx($aImg);
      }
  
      static function GetHeight($aImg) {
          return imagesy($aImg);
      }
  
      static function CreateFromString($aStr) {
          $img = imagecreatefromstring($aStr);
          if( $img === false ) {
              JpGraphError::RaiseL(25085);
              //('An image can not be created from the supplied string. It is either in a format not supported or the string is representing an corrupt image.');
          }
          return $img;
      }
  
      function SetCanvasH($aHdl) {
          $this->img = $aHdl;
          $this->rgb->img = $aHdl;
      }
  
      function SetCanvasColor($aColor) {
          $this->canvascolor = $aColor ;
      }
  
      function SetAlphaBlending($aFlg=true) {
          ImageAlphaBlending($this->img,$aFlg);
      }
  
      function SetAutoMargin() {
          $min_bm=5;
          $lm = min(40,$this->width/7);
          $rm = min(20,$this->width/10);
          $tm = max(5,$this->height/7);
          $bm = max($min_bm,$this->height/6);
          $this->SetMargin($lm,$rm,$tm,$bm);
      }
  
      //---------------
      // PUBLIC METHODS
  
      function SetFont($family,$style=FS_NORMAL,$size=10) {
          $this->font_family=$family;
          $this->font_style=$style;
          $this->font_size=$size*SUPERSAMPLING_SCALE;
          $this->font_file='';
          if( ($this->font_family==FF_FONT1 || $this->font_family==FF_FONT2) && $this->font_style==FS_BOLD ){
              ++$this->font_family;
          }
          if( $this->font_family > FF_FONT2+1 ) { // A TTF font so get the font file
  
              // Check that this PHP has support for TTF fonts
              if( !function_exists('imagettfbbox') ) {
                  // use internal font when php is configured without '--with-ttf'
                  $this->font_family = FF_FONT1;
  //                JpGraphError::RaiseL(25087);//('This PHP build has not been configured with TTF support. You need to recompile your PHP installation with FreeType support.');
              } else {
                  $this->font_file = $this->ttf->File($this->font_family,$this->font_style);
              }
          }
      }
  
      // Get the specific height for a text string
      function GetTextHeight($txt="",$angle=0) {
          $tmp = preg_split('/\n/',$txt);
          $n = count($tmp);
          $m=0;
          for($i=0; $i< $n; ++$i) {
              $m = max($m,strlen($tmp[$i]));
          }
  
          if( $this->font_family <= FF_FONT2+1 ) {
              if( $angle==0 ) {
                  $h = imagefontheight($this->font_family);
                  if( $h === false ) {
                      JpGraphError::RaiseL(25088);//('You have a misconfigured GD font support. The call to imagefontwidth() fails.');
                  }
  
                  return $n*$h;
              }
              else {
                  $w = @imagefontwidth($this->font_family);
                  if( $w === false ) {
                      JpGraphError::RaiseL(25088);//('You have a misconfigured GD font support. The call to imagefontwidth() fails.');
                  }
  
                  return $m*$w;
              }
          }
          else {
              $bbox = $this->GetTTFBBox($txt,$angle);
              return $bbox[1]-$bbox[5]+1;
          }
      }
  
      // Estimate font height
      function GetFontHeight($angle=0) {
          $txt = "XOMg";
          return $this->GetTextHeight($txt,$angle);
      }
  
      // Approximate font width with width of letter "O"
      function GetFontWidth($angle=0) {
          $txt = 'O';
          return $this->GetTextWidth($txt,$angle);
      }
  
      // Get actual width of text in absolute pixels. Note that the width is the
      // texts projected with onto the x-axis. Call with angle=0 to get the true
      // etxt width.
      function GetTextWidth($txt,$angle=0) {
  
          $tmp = preg_split('/\n/',$txt);
          $n = count($tmp);
          if( $this->font_family <= FF_FONT2+1 ) {
  
              $m=0;
              for($i=0; $i < $n; ++$i) {
                  $l=strlen($tmp[$i]);
                  if( $l > $m ) {
                      $m = $l;
                  }
              }
  
              if( $angle==0 ) {
                  $w = @imagefontwidth($this->font_family);
                  if( $w === false ) {
                      JpGraphError::RaiseL(25088);//('You have a misconfigured GD font support. The call to imagefontwidth() fails.');
                  }
                  return $m*$w;
              }
              else {
                  // 90 degrees internal so height becomes width
                  $h = @imagefontheight($this->font_family);
                  if( $h === false ) {
                      JpGraphError::RaiseL(25089);//('You have a misconfigured GD font support. The call to imagefontheight() fails.');
                  }
                  return $n*$h;
              }
          }
          else {
              // For TTF fonts we must walk through a lines and find the
              // widest one which we use as the width of the multi-line
              // paragraph
              $m=0;
              for( $i=0; $i < $n; ++$i ) {
                  $bbox = $this->GetTTFBBox($tmp[$i],$angle);
                  $mm =  $bbox[2] - $bbox[0];
                  if( $mm > $m )
                      $m = $mm;
              }
              return $m;
          }
      }
  
  
      // Draw text with a box around it
      function StrokeBoxedText($x,$y,$txt,$dir=0,$fcolor="white",$bcolor="black",
                               $shadowcolor=false,$paragraph_align="left",
                               $xmarg=6,$ymarg=4,$cornerradius=0,$dropwidth=3) {
  
  		$oldx = $this->lastx;
  		$oldy = $this->lasty;
  
          if( !is_numeric($dir) ) {
              if( $dir=="h" ) $dir=0;
              elseif( $dir=="v" ) $dir=90;
              else JpGraphError::RaiseL(25090,$dir);//(" Unknown direction specified in call to StrokeBoxedText() [$dir]");
          }
  
          if( $this->font_family >= FF_FONT0 && $this->font_family <= FF_FONT2+1) {
              $width=$this->GetTextWidth($txt,$dir) ;
              $height=$this->GetTextHeight($txt,$dir) ;
          }
          else {
              $width=$this->GetBBoxWidth($txt,$dir) ;
              $height=$this->GetBBoxHeight($txt,$dir) ;
          }
  
          $height += 2*$ymarg;
          $width  += 2*$xmarg;
  
          if( $this->text_halign=="right" )      $x -= $width;
          elseif( $this->text_halign=="center" ) $x -= $width/2;
  
          if( $this->text_valign=="bottom" )     $y -= $height;
          elseif( $this->text_valign=="center" ) $y -= $height/2;
  
          $olda = $this->SetAngle(0);
  
          if( $shadowcolor ) {
              $this->PushColor($shadowcolor);
              $this->FilledRoundedRectangle($x-$xmarg+$dropwidth,$y-$ymarg+$dropwidth,
                                            $x+$width+$dropwidth,$y+$height-$ymarg+$dropwidth,
                                            $cornerradius);
              $this->PopColor();
              $this->PushColor($fcolor);
              $this->FilledRoundedRectangle($x-$xmarg,$y-$ymarg,
                                            $x+$width,$y+$height-$ymarg,
                                            $cornerradius);
              $this->PopColor();
              $this->PushColor($bcolor);
              $this->RoundedRectangle($x-$xmarg,$y-$ymarg,
                                      $x+$width,$y+$height-$ymarg,$cornerradius);
              $this->PopColor();
          }
          else {
              if( $fcolor ) {
                  $oc=$this->current_color;
                  $this->SetColor($fcolor);
                  $this->FilledRoundedRectangle($x-$xmarg,$y-$ymarg,$x+$width,$y+$height-$ymarg,$cornerradius);
                  $this->current_color=$oc;
              }
              if( $bcolor ) {
                  $oc=$this->current_color;
                  $this->SetColor($bcolor);
                  $this->RoundedRectangle($x-$xmarg,$y-$ymarg,$x+$width,$y+$height-$ymarg,$cornerradius);
                  $this->current_color=$oc;
              }
          }
  
          $h=$this->text_halign;
          $v=$this->text_valign;
          $this->SetTextAlign("left","top");
  
          $debug=false;
          $this->StrokeText($x, $y, $txt, $dir, $paragraph_align,$debug);
  
          $bb = array($x-$xmarg,$y+$height-$ymarg,$x+$width,$y+$height-$ymarg,
                      $x+$width,$y-$ymarg,$x-$xmarg,$y-$ymarg);
          $this->SetTextAlign($h,$v);
  
          $this->SetAngle($olda);
  		$this->lastx = $oldx;
  		$this->lasty = $oldy;
  
          return $bb;
      }
  
      // Draw text with a box around it. This time the box will be rotated
      // with the text. The previous method will just make a larger enough non-rotated
      // box to hold the text inside.
      function StrokeBoxedText2($x,$y,$txt,$dir=0,$fcolor="white",$bcolor="black",
                               $shadowcolor=false,$paragraph_align="left",
                               $xmarg=6,$ymarg=4,$cornerradius=0,$dropwidth=3) {
  
         // This version of boxed text will stroke a rotated box round the text
         // thta will follow the angle of the text.
         // This has two implications:
         // 1) This methos will only support TTF fonts
         // 2) The only two alignment that makes sense are centered or baselined
  
         if( $this->font_family <= FF_FONT2+1 ) {
             JpGraphError::RaiseL(25131);//StrokeBoxedText2() Only support TTF fonts and not built in bitmap fonts
         }
  
  		$oldx = $this->lastx;
  		$oldy = $this->lasty;
          $dir = $this->NormAngle($dir);
  
          if( !is_numeric($dir) ) {
              if( $dir=="h" ) $dir=0;
              elseif( $dir=="v" ) $dir=90;
              else JpGraphError::RaiseL(25090,$dir);//(" Unknown direction specified in call to StrokeBoxedText() [$dir]");
          }
  
          $width=$this->GetTextWidth($txt,0) + 2*$xmarg;
          $height=$this->GetTextHeight($txt,0) + 2*$ymarg ;
          $rect_width=$this->GetBBoxWidth($txt,$dir) ;
          $rect_height=$this->GetBBoxHeight($txt,$dir) ;
  
          $baseline_offset = $this->bbox_cache[1]-1;
  
          if( $this->text_halign=="center" ) {
              if( $dir >= 0 && $dir <= 90 ) {
  
                  $x -= $rect_width/2;
                  $x += sin($dir*M_PI/180)*$height;
                  $y += $rect_height/2;                
  
              } elseif( $dir >= 270 && $dir <= 360 ) {
  
                  $x -= $rect_width/2;
                  $y -= $rect_height/2;
                  $y += cos($dir*M_PI/180)*$height;
  
              } elseif( $dir >= 90 && $dir <= 180 ) {
  
                  $x += $rect_width/2;
                  $y += $rect_height/2;
                  $y += cos($dir*M_PI/180)*$height;
  
              }
              else {
                  // $dir > 180 &&  $dir < 270
                  $x += $rect_width/2;
                  $x += sin($dir*M_PI/180)*$height;
                  $y -= $rect_height/2;
              }
          }
  
          // Rotate the box around this point
          $this->SetCenter($x,$y);
          $olda = $this->SetAngle(-$dir);
  
          // We need to use adjusted coordinats for the box to be able
          // to draw the box below the baseline. This cannot be done before since
          // the rotating point must be the original x,y since that is arounbf the
          // point where the text will rotate and we cannot change this since
          // that is where the GD/GreeType will rotate the text
  
  
          // For smaller <14pt font we need to do some additional
          // adjustments to make it look good
          if( $this->font_size < 14 ) {
              $x -= 2;
              $y += 2;
          }
          else {
            //  $y += $baseline_offset;
          }
  
          if( $shadowcolor ) {
              $this->PushColor($shadowcolor);
              $this->FilledRectangle($x-$xmarg+$dropwidth,$y+$ymarg+$dropwidth-$height,
                                            $x+$width+$dropwidth,$y+$ymarg+$dropwidth);
                                            //$cornerradius);
              $this->PopColor();
              $this->PushColor($fcolor);
              $this->FilledRectangle($x-$xmarg, $y+$ymarg-$height,
                                            $x+$width, $y+$ymarg);
                                            //$cornerradius);
              $this->PopColor();
              $this->PushColor($bcolor);
              $this->Rectangle($x-$xmarg,$y+$ymarg-$height,
                                      $x+$width,$y+$ymarg);
                                      //$cornerradius);
              $this->PopColor();
          }
          else {
              if( $fcolor ) {
                  $oc=$this->current_color;
                  $this->SetColor($fcolor);
                  $this->FilledRectangle($x-$xmarg,$y+$ymarg-$height,$x+$width,$y+$ymarg);//,$cornerradius);
                  $this->current_color=$oc;
              }
              if( $bcolor ) {
                  $oc=$this->current_color;
                  $this->SetColor($bcolor);
                  $this->Rectangle($x-$xmarg,$y+$ymarg-$height,$x+$width,$y+$ymarg);//,$cornerradius);
                  $this->current_color=$oc;
              }
          }
  
          if( $this->font_size < 14 ) {
              $x += 2;
              $y -= 2;
          }
          else {
  
              // Restore the original y before we stroke the text
             // $y -= $baseline_offset;
  
          }
  
          $this->SetCenter(0,0);
          $this->SetAngle($olda);
  
          $h=$this->text_halign;
          $v=$this->text_valign;
          if( $this->text_halign == 'center') {
              $this->SetTextAlign('center','basepoint');
          }
          else {
              $this->SetTextAlign('basepoint','basepoint');
          }
  
          $debug=false;
          $this->StrokeText($x, $y, $txt, $dir, $paragraph_align,$debug);
  
          $bb = array($x-$xmarg, $y+$height-$ymarg,
                      $x+$width, $y+$height-$ymarg,
                      $x+$width, $y-$ymarg,
                      $x-$xmarg, $y-$ymarg);
  
          $this->SetTextAlign($h,$v);
          $this->SetAngle($olda);
  
  		$this->lastx = $oldx;
  		$this->lasty = $oldy;
  
          return $bb;
      }
  
      // Set text alignment
      function SetTextAlign($halign,$valign="bottom") {
          $this->text_halign=$halign;
          $this->text_valign=$valign;
      }
  
      function _StrokeBuiltinFont($x,$y,$txt,$dir,$paragraph_align,&$aBoundingBox,$aDebug=false) {
  
          if( is_numeric($dir) && $dir!=90 && $dir!=0)
          JpGraphError::RaiseL(25091);//(" Internal font does not support drawing text at arbitrary angle. Use TTF fonts instead.");
  
          $h=$this->GetTextHeight($txt);
          $fh=$this->GetFontHeight();
          $w=$this->GetTextWidth($txt);
  
          if( $this->text_halign=="right") {
              $x -= $dir==0 ? $w : $h;
          }
          elseif( $this->text_halign=="center" ) {
              // For center we subtract 1 pixel since this makes the middle
              // be prefectly in the middle
              $x -= $dir==0 ? $w/2-1 : $h/2;
          }
          if( $this->text_valign=="top" ) {
              $y += $dir==0 ? $h : $w;
          }
          elseif( $this->text_valign=="center" ) {
              $y += $dir==0 ? $h/2 : $w/2;
          }
  
          $use_font = $this->font_family;
  
          if( $dir==90 ) {
              imagestringup($this->img,$use_font,$x,$y,$txt,$this->current_color);
              $aBoundingBox = array(round($x),round($y),round($x),round($y-$w),round($x+$h),round($y-$w),round($x+$h),round($y));
              if( $aDebug ) {
                  // Draw bounding box
                  $this->PushColor('green');
                  $this->Polygon($aBoundingBox,true);
                  $this->PopColor();
              }
          }
          else {
              if( preg_match('/\n/',$txt) ) {
                  $tmp = preg_split('/\n/',$txt);
                  for($i=0; $i < count($tmp); ++$i) {
                      $w1 = $this->GetTextWidth($tmp[$i]);
                      if( $paragraph_align=="left" ) {
                          imagestring($this->img,$use_font,$x,$y-$h+1+$i*$fh,$tmp[$i],$this->current_color);
                      }
                      elseif( $paragraph_align=="right" ) {
                          imagestring($this->img,$use_font,$x+($w-$w1),$y-$h+1+$i*$fh,$tmp[$i],$this->current_color);
                      }
                      else {
                          imagestring($this->img,$use_font,$x+$w/2-$w1/2,$y-$h+1+$i*$fh,$tmp[$i],$this->current_color);
                      }
                  }
              }
              else {
                  //Put the text
                  imagestring($this->img,$use_font,$x,$y-$h+1,$txt,$this->current_color);
              }
              if( $aDebug ) {
                  // Draw the bounding rectangle and the bounding box
                  $p1 = array(round($x),round($y),round($x),round($y-$h),round($x+$w),round($y-$h),round($x+$w),round($y));
  
                  // Draw bounding box
                  $this->PushColor('green');
                  $this->Polygon($p1,true);
                  $this->PopColor();
  
              }
              $aBoundingBox=array(round($x),round($y),round($x),round($y-$h),round($x+$w),round($y-$h),round($x+$w),round($y));
          }
      }
  
      function AddTxtCR($aTxt) {
          // If the user has just specified a '\n'
          // instead of '\n\t' we have to add '\r' since
          // the width will be too muchy otherwise since when
          // we print we stroke the individually lines by hand.
          $e = explode("\n",$aTxt);
          $n = count($e);
          for($i=0; $i<$n; ++$i) {
              $e[$i]=str_replace("\r","",$e[$i]);
          }
          return implode("\n\r",$e);
      }
  
      function NormAngle($a) {
          // Normalize angle in degrees
          // Normalize angle to be between 0-360
          while( $a > 360 )
              $a -= 360;
          while( $a < -360 )
              $a += 360;
          if( $a < 0 )
              $a = 360 + $a;
          return $a;
      }
  
      function imagettfbbox_fixed($size, $angle, $fontfile, $text) {
  
  
          if( ! USE_LIBRARY_IMAGETTFBBOX ) {
  
              $bbox = @imagettfbbox($size, $angle, $fontfile, $text);
              if( $bbox === false ) {
                  JpGraphError::RaiseL(25092,$this->font_file);
                  //("There is either a configuration problem with TrueType or a problem reading font file (".$this->font_file."). Make sure file exists and is in a readable place for the HTTP process. (If 'basedir' restriction is enabled in PHP then the font file must be located in the document root.). It might also be a wrongly installed FreeType library. Try uppgrading to at least FreeType 2.1.13 and recompile GD with the correct setup so it can find the new FT library.");
              }
              $this->bbox_cache = $bbox;
              return $bbox;
          }
  
          // The built in imagettfbbox is buggy for angles != 0 so
          // we calculate this manually by getting the bounding box at
          // angle = 0 and then rotate the bounding box manually
          $bbox = @imagettfbbox($size, 0, $fontfile, $text);
          if( $bbox === false ) {
              JpGraphError::RaiseL(25092,$this->font_file);
              //("There is either a configuration problem with TrueType or a problem reading font file (".$this->font_file."). Make sure file exists and is in a readable place for the HTTP process. (If 'basedir' restriction is enabled in PHP then the font file must be located in the document root.). It might also be a wrongly installed FreeType library. Try uppgrading to at least FreeType 2.1.13 and recompile GD with the correct setup so it can find the new FT library.");
          }
  
          $angle = $this->NormAngle($angle);
  
          $a = $angle*M_PI/180;
          $ca = cos($a);
          $sa = sin($a);
          $ret = array();
  
          // We always add 1 pixel to the left since the left edge of the bounding
          // box is sometimes coinciding with the first pixel of the text
          //$bbox[0] -= 1;
          //$bbox[6] -= 1;
          
          // For roatated text we need to add extra width for rotated
          // text since the kerning and stroking of the TTF is not the same as for
          // text at a 0 degree angle
  
          if( $angle > 0.001 && abs($angle-360) > 0.001 ) {
              $h = abs($bbox[7]-$bbox[1]);
              $w = abs($bbox[2]-$bbox[0]);
  
              $bbox[0] -= 2;
              $bbox[6] -= 2;
              // The width is underestimated so compensate for that
              $bbox[2] += round($w*0.06);
              $bbox[4] += round($w*0.06);
  
              // and we also need to compensate with increased height
              $bbox[5] -= round($h*0.1);
              $bbox[7] -= round($h*0.1);
  
              if( $angle > 90 ) {
                  // For angles > 90 we also need to extend the height further down
                  // by the baseline since that is also one more problem
                  $bbox[1] += round($h*0.15);
                  $bbox[3] += round($h*0.15);
  
                  // and also make it slighty less height
                  $bbox[7] += round($h*0.05);
                  $bbox[5] += round($h*0.05);
  
                  // And we need to move the box slightly top the rright (from a tetx perspective)
                  $bbox[0] += round($w*0.02);
                  $bbox[6] += round($w*0.02);
  
                  if( $angle > 180 ) {
                      // And we need to move the box slightly to the left (from a text perspective)
                      $bbox[0] -= round($w*0.02);
                      $bbox[6] -= round($w*0.02);
                      $bbox[2] -= round($w*0.02);
                      $bbox[4] -= round($w*0.02);
  
                  }
  
              }
              for($i = 0; $i < 7; $i += 2) {
                  $ret[$i] = round($bbox[$i] * $ca + $bbox[$i+1] * $sa);
                  $ret[$i+1] = round($bbox[$i+1] * $ca - $bbox[$i] * $sa);
              }
              $this->bbox_cache = $ret;
              return $ret;
          }
          else {
              $this->bbox_cache = $bbox;
              return $bbox;
          }
      }
  
      // Deprecated
      function GetTTFBBox($aTxt,$aAngle=0) {
          $bbox = $this->imagettfbbox_fixed($this->font_size,$aAngle,$this->font_file,$aTxt);
           return $bbox;
      }
  
      function GetBBoxTTF($aTxt,$aAngle=0) {
          // Normalize the bounding box to become a minimum
          // enscribing rectangle
  
          $aTxt = $this->AddTxtCR($aTxt);
  
          if( !is_readable($this->font_file) ) {
              JpGraphError::RaiseL(25093,$this->font_file);
              //('Can not read font file ('.$this->font_file.') in call to Image::GetBBoxTTF. Please make sure that you have set a font before calling this method and that the font is installed in the TTF directory.');
          }
          $bbox = $this->imagettfbbox_fixed($this->font_size,$aAngle,$this->font_file,$aTxt);
  
          if( $aAngle==0 ) return $bbox;
  
          if( $aAngle >= 0 ) {
              if(  $aAngle <= 90 ) { //<=0
                  $bbox = array($bbox[6],$bbox[1],$bbox[2],$bbox[1],
                                $bbox[2],$bbox[5],$bbox[6],$bbox[5]);
              }
              elseif(  $aAngle <= 180 ) { //<= 2
                  $bbox = array($bbox[4],$bbox[7],$bbox[0],$bbox[7],
                                $bbox[0],$bbox[3],$bbox[4],$bbox[3]);
              }
              elseif(  $aAngle <= 270 )  { //<= 3
                  $bbox = array($bbox[2],$bbox[5],$bbox[6],$bbox[5],
                                $bbox[6],$bbox[1],$bbox[2],$bbox[1]);
              }
              else {
                  $bbox = array($bbox[0],$bbox[3],$bbox[4],$bbox[3],
                                $bbox[4],$bbox[7],$bbox[0],$bbox[7]);
              }
          }
          elseif(  $aAngle < 0 ) {
              if( $aAngle <= -270 ) { // <= -3
                  $bbox = array($bbox[6],$bbox[1],$bbox[2],$bbox[1],
                                $bbox[2],$bbox[5],$bbox[6],$bbox[5]);
              }
              elseif( $aAngle <= -180 ) { // <= -2
                  $bbox = array($bbox[0],$bbox[3],$bbox[4],$bbox[3],
                                $bbox[4],$bbox[7],$bbox[0],$bbox[7]);
              }
              elseif( $aAngle <= -90 ) { // <= -1
                  $bbox = array($bbox[2],$bbox[5],$bbox[6],$bbox[5],
                                $bbox[6],$bbox[1],$bbox[2],$bbox[1]);
              }
              else {
                  $bbox = array($bbox[0],$bbox[3],$bbox[4],$bbox[3],
                                $bbox[4],$bbox[7],$bbox[0],$bbox[7]);
              }
          }
          return $bbox;
      }
  
      function GetBBoxHeight($aTxt,$aAngle=0) {
          $box = $this->GetBBoxTTF($aTxt,$aAngle);
          return abs($box[7]-$box[1]);
      }
  
      function GetBBoxWidth($aTxt,$aAngle=0) {
          $box = $this->GetBBoxTTF($aTxt,$aAngle);
          return $box[2]-$box[0]+1;
      }
  
  
      function _StrokeTTF($x,$y,$txt,$dir,$paragraph_align,&$aBoundingBox,$debug=false) {
  
          // Setup default inter line margin for paragraphs to be
          // 3% of the font height.
          $ConstLineSpacing = 0.03 ;
  
          // Remember the anchor point before adjustment
          if( $debug ) {
              $ox=$x;
              $oy=$y;
          }
  
          if( !preg_match('/\n/',$txt) || ($dir>0 && preg_match('/\n/',$txt)) ) {
              // Format a single line
  
              $txt = $this->AddTxtCR($txt);
              $bbox=$this->GetBBoxTTF($txt,$dir);
              $width  = $this->GetBBoxWidth($txt,$dir);
              $height = $this->GetBBoxHeight($txt,$dir);
  
              // The special alignment "basepoint" is mostly used internally
              // in the library. This will put the anchor position at the left
              // basepoint of the tetx. This is the default anchor point for
              // TTF text.
  
              if( $this->text_valign != 'basepoint' ) {
                  // Align x,y ot lower left corner of bbox
                  
  
                  if( $this->text_halign=='right' ) {
                      $x -= $width;
                      $x -= $bbox[0];
                  }
                  elseif( $this->text_halign=='center' ) {
                      $x -= $width/2;
                      $x -= $bbox[0];
                  }
                  elseif( $this->text_halign=='baseline' ) {
                      // This is only support for text at 90 degree !!
                      // Do nothing the text is drawn at baseline by default
                  }
  
                  if( $this->text_valign=='top' ) {
                      $y -= $bbox[1]; // Adjust to bottom of text
                      $y += $height;
                  }
                  elseif( $this->text_valign=='center' ) {
                      $y -= $bbox[1]; // Adjust to bottom of text
                      $y += $height/2;
                  }
                  elseif( $this->text_valign=='baseline' ) {
                      // This is only support for text at 0 degree !!
                      // Do nothing the text is drawn at baseline by default
                  }
              } 
              ImageTTFText ($this->img, $this->font_size, $dir, $x, $y,
                            $this->current_color,$this->font_file,$txt);
  
              // Calculate and return the co-ordinates for the bounding box
              $box = $this->imagettfbbox_fixed($this->font_size,$dir,$this->font_file,$txt);
              $p1 = array();
  
              for($i=0; $i < 4; ++$i) {
                  $p1[] = round($box[$i*2]+$x);
                  $p1[] = round($box[$i*2+1]+$y);
              }
              $aBoundingBox = $p1;
  
              // Debugging code to highlight the bonding box and bounding rectangle
              // For text at 0 degrees the bounding box and bounding rectangle are the
              // same
              if( $debug ) {
              // Draw the bounding rectangle and the bounding box
  
                  $p = array();
                  $p1 = array();
  
                  for($i=0; $i < 4; ++$i) {
                      $p[] =  $bbox[$i*2]+$x ;
                      $p[] =  $bbox[$i*2+1]+$y;
                      $p1[] = $box[$i*2]+$x ;
                      $p1[] = $box[$i*2+1]+$y ;
                  }
  
                  // Draw bounding box
                  $this->PushColor('green');
                  $this->Polygon($p1,true);
                  $this->PopColor();
  
                  // Draw bounding rectangle
                  $this->PushColor('darkgreen');
                  $this->Polygon($p,true);
                  $this->PopColor();
  
                  // Draw a cross at the anchor point
                  $this->PushColor('red');
                  $this->Line($ox-15,$oy,$ox+15,$oy);
                  $this->Line($ox,$oy-15,$ox,$oy+15);
                  $this->PopColor();
              }
          }
          else {
              // Format a text paragraph
              $fh=$this->GetFontHeight();
  
              // Line margin is 25% of font height
              $linemargin=round($fh*$ConstLineSpacing);
              $fh += $linemargin;
              $w=$this->GetTextWidth($txt);
  
              $y -= $linemargin/2;
              $tmp = preg_split('/\n/',$txt);
              $nl = count($tmp);
              $h = $nl * $fh;
  
              if( $this->text_halign=='right') {
                  $x -= $dir==0 ? $w : $h;
              }
              elseif( $this->text_halign=='center' ) {
                  $x -= $dir==0 ? $w/2 : $h/2;
              }
  
              if( $this->text_valign=='top' ) {
                  $y += $dir==0 ? $h : $w;
              }
              elseif( $this->text_valign=='center' ) {
                  $y += $dir==0 ? $h/2 : $w/2;
              }
  
              // Here comes a tricky bit.
              // Since we have to give the position for the string at the
              // baseline this means thaht text will move slightly up
              // and down depending on any of it's character descend below
              // the baseline, for example a 'g'. To adjust the Y-position
              // we therefore adjust the text with the baseline Y-offset
              // as used for the current font and size. This will keep the
              // baseline at a fixed positoned disregarding the actual
              // characters in the string.
              $standardbox = $this->GetTTFBBox('Gg',$dir);
              $yadj = $standardbox[1];
              $xadj = $standardbox[0];
              $aBoundingBox = array();
              for($i=0; $i < $nl; ++$i) {
                  $wl = $this->GetTextWidth($tmp[$i]);
                  $bbox = $this->GetTTFBBox($tmp[$i],$dir);
                  if( $paragraph_align=='left' ) {
                      $xl = $x;
                  }
                  elseif( $paragraph_align=='right' ) {
                      $xl = $x + ($w-$wl);
                  }
                  else {
                      // Center
                      $xl = $x + $w/2 - $wl/2 ;
                  }
  
                  // In theory we should adjust with full pre-lead to get the lines
                  // lined up but this doesn't look good so therfore we only adjust with
                  // half th pre-lead
                  $xl -= $bbox[0]/2;
                  $yl = $y - $yadj;
                  //$xl = $xl- $xadj;
                  ImageTTFText($this->img, $this->font_size, $dir, $xl, $yl-($h-$fh)+$fh*$i,
                               $this->current_color,$this->font_file,$tmp[$i]);
  
                 // echo "xl=$xl,".$tmp[$i]." <br>";
                  if( $debug  ) {
                      // Draw the bounding rectangle around each line
                      $box=@ImageTTFBBox($this->font_size,$dir,$this->font_file,$tmp[$i]);
                      $p = array();
                      for($j=0; $j < 4; ++$j) {
                          $p[] = $bbox[$j*2]+$xl;
                          $p[] = $bbox[$j*2+1]+$yl-($h-$fh)+$fh*$i;
                      }
  
                      // Draw bounding rectangle
                      $this->PushColor('darkgreen');
                      $this->Polygon($p,true);
                      $this->PopColor();
                  }
              }
  
              // Get the bounding box
              $bbox = $this->GetBBoxTTF($txt,$dir);
              for($j=0; $j < 4; ++$j) {
                  $bbox[$j*2]+= round($x);
                  $bbox[$j*2+1]+= round($y - ($h-$fh) - $yadj);
              }
              $aBoundingBox = $bbox;
  
              if( $debug ) {
                  // Draw a cross at the anchor point
                  $this->PushColor('red');
                  $this->Line($ox-25,$oy,$ox+25,$oy);
                  $this->Line($ox,$oy-25,$ox,$oy+25);
                  $this->PopColor();
              }
  
          }
      }
  
      function StrokeText($x,$y,$txt,$dir=0,$paragraph_align="left",$debug=false) {
  
          $x = round($x);
          $y = round($y);
  
          // Do special language encoding
          $txt = $this->langconv->Convert($txt,$this->font_family);
  
          if( !is_numeric($dir) ) {
              JpGraphError::RaiseL(25094);//(" Direction for text most be given as an angle between 0 and 90.");
          }
  
          if( $this->font_family >= FF_FONT0 && $this->font_family <= FF_FONT2+1) {
              $this->_StrokeBuiltinFont($x,$y,$txt,$dir,$paragraph_align,$boundingbox,$debug);
          }
          elseif( $this->font_family >= _FIRST_FONT && $this->font_family <= _LAST_FONT)  {
              $this->_StrokeTTF($x,$y,$txt,$dir,$paragraph_align,$boundingbox,$debug);
          }
          else {
              JpGraphError::RaiseL(25095);//(" Unknown font font family specification. ");
          }
          return $boundingbox;
      }
  
      function SetMargin($lm,$rm,$tm,$bm) {
  
          $this->left_margin=$lm;
          $this->right_margin=$rm;
          $this->top_margin=$tm;
          $this->bottom_margin=$bm;
  
          $this->plotwidth  = $this->width  - $this->left_margin - $this->right_margin;
          $this->plotheight = $this->height - $this->top_margin  - $this->bottom_margin;
  
          if( $this->width  > 0 && $this->height > 0 ) {
              if( $this->plotwidth < 0  || $this->plotheight < 0 ) {
              	JpGraphError::RaiseL(25130, $this->plotwidth, $this->plotheight);
                  //JpGraphError::raise("To small plot area. ($lm,$rm,$tm,$bm : $this->plotwidth x $this->plotheight). With the given image size and margins there is to little space left for the plot. Increase the plot size or reduce the margins.");
              }
          }
      }
  
      function SetTransparent($color) {
          imagecolortransparent ($this->img,$this->rgb->allocate($color));
      }
  
      function SetColor($color,$aAlpha=0) {
          $this->current_color_name = $color;
          $this->current_color=$this->rgb->allocate($color,$aAlpha);
          if( $this->current_color == -1 ) {
              $tc=imagecolorstotal($this->img);
              JpGraphError::RaiseL(25096);
              //("Can't allocate any more colors. Image has already allocated maximum of <b>$tc colors</b>. This might happen if you have anti-aliasing turned on together with a background image or perhaps gradient fill since this requires many, many colors. Try to turn off anti-aliasing. If there is still a problem try downgrading the quality of the background image to use a smaller pallete to leave some entries for your graphs. You should try to limit the number of colors in your background image to 64. If there is still problem set the constant DEFINE(\"USE_APPROX_COLORS\",true); in jpgraph.php This will use approximative colors when the palette is full. Unfortunately there is not much JpGraph can do about this since the palette size is a limitation of current graphic format and what the underlying GD library suppports.");
          }
          return $this->current_color;
      }
  
      function PushColor($color) {
          if( $color != "" ) {
              $this->colorstack[$this->colorstackidx]=$this->current_color_name;
              $this->colorstack[$this->colorstackidx+1]=$this->current_color;
              $this->colorstackidx+=2;
              $this->SetColor($color);
          }
          else {
              JpGraphError::RaiseL(25097);//("Color specified as empty string in PushColor().");
          }
      }
  
      function PopColor() {
          if( $this->colorstackidx < 1 ) {
              JpGraphError::RaiseL(25098);//(" Negative Color stack index. Unmatched call to PopColor()");
          }
          $this->current_color=$this->colorstack[--$this->colorstackidx];
          $this->current_color_name=$this->colorstack[--$this->colorstackidx];
      }
  
  
      function SetLineWeight($weight) {
          $old = $this->line_weight;
          imagesetthickness($this->img,$weight);
          $this->line_weight = $weight;
          return $old;
      }
  
      function SetStartPoint($x,$y) {
          $this->lastx=round($x);
          $this->lasty=round($y);
      }
  
      function Arc($cx,$cy,$w,$h,$s,$e) {
          // GD Arc doesn't like negative angles
          while( $s < 0) $s += 360;
          while( $e < 0) $e += 360;
          imagearc($this->img,round($cx),round($cy),round($w),round($h),$s,$e,$this->current_color);
      }
  
      function FilledArc($xc,$yc,$w,$h,$s,$e,$style='') {
          $s = round($s);
          $e = round($e);
          while( $s < 0 ) $s += 360;
          while( $e < 0 ) $e += 360;
          if( $style=='' )
          $style=IMG_ARC_PIE;
          if( abs($s-$e) > 0 ) {
              imagefilledarc($this->img,round($xc),round($yc),round($w),round($h),$s,$e,$this->current_color,$style);
  //            $this->DrawImageSmoothArc($this->img,round($xc),round($yc),round($w),round($h),$s,$e,$this->current_color,$style);
          }
      }
  
      function FilledCakeSlice($cx,$cy,$w,$h,$s,$e) {
          $this->CakeSlice($cx,$cy,$w,$h,$s,$e,$this->current_color_name);
      }
  
      function CakeSlice($xc,$yc,$w,$h,$s,$e,$fillcolor="",$arccolor="") {
          $s = round($s); $e = round($e);
          $w = round($w); $h = round($h);
          $xc = round($xc); $yc = round($yc);
          if( $s == $e ) {
              // A full circle. We draw this a plain circle
              $this->PushColor($fillcolor);
              imagefilledellipse($this->img,$xc,$yc,2*$w,2*$h,$this->current_color);
  
              // If antialiasing is used then we often don't have any color no the surrounding
              // arc. So, we need to check for this special case so we don't send an empty
              // color to the push function. In this case we use the fill color for the arc as well
              if( $arccolor != '' ) {
                  $this->PopColor();
                  $this->PushColor($arccolor);
              }
              imageellipse($this->img,$xc,$yc,2*$w,2*$h,$this->current_color);
              $this->Line($xc,$yc,cos($s*M_PI/180)*$w+$xc,$yc+sin($s*M_PI/180)*$h);
              $this->PopColor();
          }
          else {
              $this->PushColor($fillcolor);
              $this->FilledArc($xc,$yc,2*$w,2*$h,$s,$e);
              $this->PopColor();
              if( $arccolor != "" ) {
                  $this->PushColor($arccolor);
                  // We add 2 pixels to make the Arc() better aligned with
                  // the filled arc.
                  imagefilledarc($this->img,$xc,$yc,2*$w,2*$h,$s,$e,$this->current_color,IMG_ARC_NOFILL | IMG_ARC_EDGED ) ;
                  $this->PopColor();
              }
          }
      }
  
      function Ellipse($xc,$yc,$w,$h) {
          $this->Arc($xc,$yc,$w,$h,0,360);
      }
  
      function Circle($xc,$yc,$r) {
          imageellipse($this->img,round($xc),round($yc),$r*2,$r*2,$this->current_color);
  //        $this->DrawImageSmoothArc($this->img,round($xc),round($yc),$r*2+1,$r*2+1,0,360,$this->current_color);
  //        $this->imageSmoothCircle($this->img, round($xc),round($yc), $r*2+1, $this->current_color);
      }
  
      function FilledCircle($xc,$yc,$r) {
          imagefilledellipse($this->img,round($xc),round($yc),2*$r,2*$r,$this->current_color);
  //        $this->DrawImageSmoothArc($this->img, round($xc), round($yc), 2*$r, 2*$r, 0, 360, $this->current_color);
      }
  
      // Linear Color InterPolation
      function lip($f,$t,$p) {
          $p = round($p,1);
          $r = $f[0] + ($t[0]-$f[0])*$p;
          $g = $f[1] + ($t[1]-$f[1])*$p;
          $b = $f[2] + ($t[2]-$f[2])*$p;
          return array($r,$g,$b);
      }
  
      // Set line style dashed, dotted etc
      function SetLineStyle($s) {
          if( is_numeric($s) ) {
              if( $s<1 || $s>4 ) {
                  JpGraphError::RaiseL(25101,$s);//(" Illegal numeric argument to SetLineStyle(): ($s)");
              }
          }
          elseif( is_string($s) ) {
              if( $s == "solid" ) $s=1;
              elseif( $s == "dotted" ) $s=2;
              elseif( $s == "dashed" ) $s=3;
              elseif( $s == "longdashed" ) $s=4;
              else {
                  JpGraphError::RaiseL(25102,$s);//(" Illegal string argument to SetLineStyle(): $s");
              }
          }
          else {
              JpGraphError::RaiseL(25103,$s);//(" Illegal argument to SetLineStyle $s");
          }
          $old = $this->line_style;
          $this->line_style=$s;
          return $old;
      }
  
      // Same as Line but take the line_style into account
      function StyleLine($x1,$y1,$x2,$y2,$aStyle='', $from_grid_class = false) {
          if( $this->line_weight <= 0 ) return;
  
          if( $aStyle === '' ) {
              $aStyle = $this->line_style;
          }
  
          $dashed_line_method = 'DashedLine';
          if ($from_grid_class) {
              $dashed_line_method = 'DashedLineForGrid';
          }
  
          // Add error check since dashed line will only work if anti-alias is disabled
          // this is a limitation in GD
  
          if( $aStyle == 1 ) {
              // Solid style. We can handle anti-aliasing for this
              $this->Line($x1,$y1,$x2,$y2);
          }
          else {
              // Since the GD routines doesn't handle AA for styled line
              // we have no option than to turn it off to get any lines at
              // all if the weight > 1
              $oldaa = $this->GetAntiAliasing();
              if( $oldaa && $this->line_weight > 1 ) {
                   $this->SetAntiAliasing(false);
              }
  
              switch( $aStyle ) {
                  case 2: // Dotted
                      $this->$dashed_line_method($x1,$y1,$x2,$y2,2,6);
                      break;
                  case 3: // Dashed
                      $this->$dashed_line_method($x1,$y1,$x2,$y2,5,9);
                      break;
                  case 4: // Longdashes
                      $this->$dashed_line_method($x1,$y1,$x2,$y2,9,13);
                      break;
                  default:
                      JpGraphError::RaiseL(25104,$this->line_style);//(" Unknown line style: $this->line_style ");
                      break;
              }
              if( $oldaa ) {
                  $this->SetAntiAliasing(true);
              }
          }
      }
  
      function DashedLine($x1,$y1,$x2,$y2,$dash_length=1,$dash_space=4) {
  
          if( $this->line_weight <= 0 ) return;
  
          // Add error check to make sure anti-alias is not enabled.
          // Dashed line does not work with anti-alias enabled. This
          // is a limitation in GD.
          if( $this->use_anti_aliasing ) {
  //            JpGraphError::RaiseL(25129); // Anti-alias can not be used with dashed lines. Please disable anti-alias or use solid lines.
          }
          
          $x1 = round($x1);
          $x2 = round($x2);
          $y1 = round($y1);
          $y2 = round($y2);
  
          $dash_length *= SUPERSAMPLING_SCALE;
          $dash_space  *= SUPERSAMPLING_SCALE;
  
          $style = array_fill(0,$dash_length,$this->current_color);
          $style = array_pad($style,$dash_space,IMG_COLOR_TRANSPARENT);
          imagesetstyle($this->img, $style);
          imageline($this->img, $x1, $y1, $x2, $y2, IMG_COLOR_STYLED);
  
          $this->lastx = $x2;
          $this->lasty = $y2;
      }
  
      function DashedLineForGrid($x1,$y1,$x2,$y2,$dash_length=1,$dash_space=4) {
  
          if( $this->line_weight <= 0 ) return;
  
          // Add error check to make sure anti-alias is not enabled.
          // Dashed line does not work with anti-alias enabled. This
          // is a limitation in GD.
          if( $this->use_anti_aliasing ) {
  //            JpGraphError::RaiseL(25129); // Anti-alias can not be used with dashed lines. Please disable anti-alias or use solid lines.
          }
          
          $x1 = round($x1);
          $x2 = round($x2);
          $y1 = round($y1);
          $y2 = round($y2);
          
          /*
          $dash_length *= $this->scale;
          $dash_space  *= $this->scale;
          */
  
          $dash_length = 2;
          $dash_length = 4;
          imagesetthickness($this->img, 1);
          $style = array_fill(0,$dash_length, $this->current_color); //hexdec('CCCCCC'));
          $style = array_pad($style,$dash_space,IMG_COLOR_TRANSPARENT);
          imagesetstyle($this->img, $style);
          imageline($this->img, $x1, $y1, $x2, $y2, IMG_COLOR_STYLED);
  
          $this->lastx = $x2;
          $this->lasty = $y2;
      }
  
      function Line($x1,$y1,$x2,$y2) {
  
          if( $this->line_weight <= 0 ) return;
  
          $x1 = round($x1);
          $x2 = round($x2);
          $y1 = round($y1);
          $y2 = round($y2);
  
          imageline($this->img,$x1,$y1,$x2,$y2,$this->current_color);
  //        $this->DrawLine($this->img, $x1, $y1, $x2, $y2, $this->line_weight, $this->current_color);
          $this->lastx=$x2;
          $this->lasty=$y2;
      }
  
      function Polygon($p,$closed=FALSE,$fast=FALSE) {
  
          if( $this->line_weight <= 0 ) return;
  
          $n=count($p);
          $oldx = $p[0];
          $oldy = $p[1];
          if( $fast ) {
              for( $i=2; $i < $n; $i+=2 ) {
                  imageline($this->img,$oldx,$oldy,$p[$i],$p[$i+1],$this->current_color);
                  $oldx = $p[$i];
                  $oldy = $p[$i+1];
              }
              if( $closed ) {
                  imageline($this->img,$p[$n*2-2],$p[$n*2-1],$p[0],$p[1],$this->current_color);
              }
          }
          else {
              for( $i=2; $i < $n; $i+=2 ) {
                  $this->StyleLine($oldx,$oldy,$p[$i],$p[$i+1]);
                  $oldx = $p[$i];
                  $oldy = $p[$i+1];
              }
              if( $closed ) {
                  $this->StyleLine($oldx,$oldy,$p[0],$p[1]);
              }
          }
      }
  
      function FilledPolygon($pts) {
          $n=count($pts);
          if( $n == 0 ) {
              JpGraphError::RaiseL(25105);//('NULL data specified for a filled polygon. Check that your data is not NULL.');
          }
          for($i=0; $i < $n; ++$i) {
              $pts[$i] = round($pts[$i]);
          }
          $old = $this->line_weight;
          imagesetthickness($this->img,1);
          imagefilledpolygon($this->img,$pts,count($pts)/2,$this->current_color);
          $this->line_weight = $old;
          imagesetthickness($this->img,$old);
      }
  
      function Rectangle($xl,$yu,$xr,$yl) {
          $this->Polygon(array($xl,$yu,$xr,$yu,$xr,$yl,$xl,$yl,$xl,$yu));
      }
  
      function FilledRectangle($xl,$yu,$xr,$yl) {
          $this->FilledPolygon(array($xl,$yu,$xr,$yu,$xr,$yl,$xl,$yl));
      }
  
      function FilledRectangle2($xl,$yu,$xr,$yl,$color1,$color2,$style=1) {
          // Fill a rectangle with lines of two colors
          if( $style===1 ) {
              // Horizontal stripe
              if( $yl < $yu ) {
                  $t = $yl; $yl=$yu; $yu=$t;
              }
              for( $y=$yu; $y <= $yl; ++$y) {
                  $this->SetColor($color1);
                  $this->Line($xl,$y,$xr,$y);
                  ++$y;
                  $this->SetColor($color2);
                  $this->Line($xl,$y,$xr,$y);
              }
          }
          else {
              if( $xl < $xl ) {
                  $t = $xl; $xl=$xr; $xr=$t;
              }
              for( $x=$xl; $x <= $xr; ++$x) {
                  $this->SetColor($color1);
                  $this->Line($x,$yu,$x,$yl);
                  ++$x;
                  $this->SetColor($color2);
                  $this->Line($x,$yu,$x,$yl);
              }
          }
      }
  
      function ShadowRectangle($xl,$yu,$xr,$yl,$fcolor=false,$shadow_width=4,$shadow_color='darkgray',$useAlpha=true) {
          // This is complicated by the fact that we must also handle the case where
          // the reactangle has no fill color
          $xl = floor($xl);
          $yu = floor($yu);
          $xr = floor($xr);
          $yl = floor($yl);
          $this->PushColor($shadow_color);
          $shadowAlpha=0;
          $this->SetLineWeight(1);
          $this->SetLineStyle('solid');
          $basecolor = $this->rgb->Color($shadow_color);
          $shadow_color = array($basecolor[0],$basecolor[1],$basecolor[2],);
          for( $i=0; $i < $shadow_width; ++$i ) {
              $this->SetColor($shadow_color,$shadowAlpha);
              $this->Line($xr-$shadow_width+$i,   $yu+$shadow_width,
                          $xr-$shadow_width+$i,   $yl-$shadow_width-1+$i);
              $this->Line($xl+$shadow_width,   $yl-$shadow_width+$i,
                          $xr-$shadow_width+$i,   $yl-$shadow_width+$i);
              if( $useAlpha ) $shadowAlpha += 1.0/$shadow_width;
          }
  
          $this->PopColor();
          if( $fcolor==false ) {
              $this->Rectangle($xl,$yu,$xr-$shadow_width-1,$yl-$shadow_width-1);
          }
          else {
              $this->PushColor($fcolor);
              $this->FilledRectangle($xl,$yu,$xr-$shadow_width-1,$yl-$shadow_width-1);
              $this->PopColor();
              $this->Rectangle($xl,$yu,$xr-$shadow_width-1,$yl-$shadow_width-1);
          }
      }
  
      function FilledRoundedRectangle($xt,$yt,$xr,$yl,$r=5) {
          if( $r==0 ) {
              $this->FilledRectangle($xt,$yt,$xr,$yl);
              return;
          }
  
          // To avoid overlapping fillings (which will look strange
          // when alphablending is enabled) we have no choice but
          // to fill the five distinct areas one by one.
  
          // Center square
          $this->FilledRectangle($xt+$r,$yt+$r,$xr-$r,$yl-$r);
          // Top band
          $this->FilledRectangle($xt+$r,$yt,$xr-$r,$yt+$r);
          // Bottom band
          $this->FilledRectangle($xt+$r,$yl-$r,$xr-$r,$yl);
          // Left band
          $this->FilledRectangle($xt,$yt+$r,$xt+$r,$yl-$r);
          // Right band
          $this->FilledRectangle($xr-$r,$yt+$r,$xr,$yl-$r);
  
          // Topleft & Topright arc
          $this->FilledArc($xt+$r,$yt+$r,$r*2,$r*2,180,270);
          $this->FilledArc($xr-$r,$yt+$r,$r*2,$r*2,270,360);
  
          // Bottomleft & Bottom right arc
          $this->FilledArc($xt+$r,$yl-$r,$r*2,$r*2,90,180);
          $this->FilledArc($xr-$r,$yl-$r,$r*2,$r*2,0,90);
  
      }
  
      function RoundedRectangle($xt,$yt,$xr,$yl,$r=5) {
  
          if( $r==0 ) {
              $this->Rectangle($xt,$yt,$xr,$yl);
              return;
          }
  
          // Top & Bottom line
          $this->Line($xt+$r,$yt,$xr-$r,$yt);
          $this->Line($xt+$r,$yl,$xr-$r,$yl);
  
          // Left & Right line
          $this->Line($xt,$yt+$r,$xt,$yl-$r);
          $this->Line($xr,$yt+$r,$xr,$yl-$r);
  
          // Topleft & Topright arc
          $this->Arc($xt+$r,$yt+$r,$r*2,$r*2,180,270);
          $this->Arc($xr-$r,$yt+$r,$r*2,$r*2,270,360);
  
          // Bottomleft & Bottomright arc
          $this->Arc($xt+$r,$yl-$r,$r*2,$r*2,90,180);
          $this->Arc($xr-$r,$yl-$r,$r*2,$r*2,0,90);
      }
  
      function FilledBevel($x1,$y1,$x2,$y2,$depth=2,$color1='white@0.4',$color2='darkgray@0.4') {
          $this->FilledRectangle($x1,$y1,$x2,$y2);
          $this->Bevel($x1,$y1,$x2,$y2,$depth,$color1,$color2);
      }
  
      function Bevel($x1,$y1,$x2,$y2,$depth=2,$color1='white@0.4',$color2='black@0.5') {
          $this->PushColor($color1);
          for( $i=0; $i < $depth; ++$i ) {
              $this->Line($x1+$i,$y1+$i,$x1+$i,$y2-$i);
              $this->Line($x1+$i,$y1+$i,$x2-$i,$y1+$i);
          }
          $this->PopColor();
  
          $this->PushColor($color2);
          for( $i=0; $i < $depth; ++$i ) {
              $this->Line($x1+$i,$y2-$i,$x2-$i,$y2-$i);
              $this->Line($x2-$i,$y1+$i,$x2-$i,$y2-$i-1);
          }
          $this->PopColor();
      }
  
      function StyleLineTo($x,$y) {
          $this->StyleLine($this->lastx,$this->lasty,$x,$y);
          $this->lastx=$x;
          $this->lasty=$y;
      }
  
      function LineTo($x,$y) {
          $this->Line($this->lastx,$this->lasty,$x,$y);
          $this->lastx=$x;
          $this->lasty=$y;
      }
  
      function Point($x,$y) {
          imagesetpixel($this->img,round($x),round($y),$this->current_color);
      }
  
      function Fill($x,$y) {
          imagefill($this->img,round($x),round($y),$this->current_color);
      }
  
      function FillToBorder($x,$y,$aBordColor) {
          $bc = $this->rgb->allocate($aBordColor);
          if( $bc == -1 ) {
              JpGraphError::RaiseL(25106);//('Image::FillToBorder : Can not allocate more colors');
          }
          imagefilltoborder($this->img,round($x),round($y),$bc,$this->current_color);
      }
  
      function SetExpired($aFlg=true) {
          $this->expired = $aFlg;
      }
  
      // Generate image header
      function Headers() {
  
          // In case we are running from the command line with the client version of
          // PHP we can't send any headers.
          $sapi = php_sapi_name();
          if( $sapi == 'cli' ) return;
  
          // These parameters are set by headers_sent() but they might cause
          // an undefined variable error unless they are initilized
          $file='';
          $lineno='';
          if( headers_sent($file,$lineno) ) {
              $file=basename($file);
              $t = new ErrMsgText();
              $msg = $t->Get(10,$file,$lineno);
              die($msg);
          }
  
          if ($this->expired) {
              header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
              header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
              header("Cache-Control: no-cache, must-revalidate");
              header("Pragma: no-cache");
          }
          header("Content-type: image/$this->img_format");
      }
  
      // Adjust image quality for formats that allow this
      function SetQuality($q) {
          $this->quality = $q;
      }
  
      // Stream image to browser or to file
      function Stream($aFile=NULL) {
          $this->DoSupersampling();
  
          $func="image".$this->img_format;
          if( $this->img_format=="jpeg" && $this->quality != null ) {
              $res = @$func($this->img,$aFile,$this->quality);
  			
  			if(!$res){
  				if($aFile != NULL){	
                      JpGraphError::RaiseL(25107,$aFile);//("Can't write to file '$aFile'. Check that the process running PHP has enough permission.");
  				}else{
                      JpGraphError::RaiseL(25108);//("Can't stream image. This is most likely due to a faulty PHP/GD setup. Try to recompile PHP and use the built-in GD library that comes with PHP.");
  				}
  		
  			}
  		}
          else {
              if( $aFile != NULL ) {
                  $res = @$func($this->img,$aFile);
                  if( !$res ) {
                      JpGraphError::RaiseL(25107,$aFile);//("Can't write to file '$aFile'. Check that the process running PHP has enough permission.");
                  }
              }
              else {
                  $res = @$func($this->img);
                  if( !$res ) {
                      JpGraphError::RaiseL(25108);//("Can't stream image. This is most likely due to a faulty PHP/GD setup. Try to recompile PHP and use the built-in GD library that comes with PHP.");
                  }
  
              }
          }
      }
  
      // Do SuperSampling using $scale
      function DoSupersampling() {
          if (SUPERSAMPLING_SCALE <= 1) {
              return $this->img;
          }
  
          $dst_img = @imagecreatetruecolor($this->original_width, $this->original_height);
          imagecopyresampled($dst_img, $this->img, 0, 0, 0, 0, $this->original_width, $this->original_height, $this->width, $this->height);
          $this->Destroy();
          return $this->img = $dst_img;
      }
  
      // Clear resources used by image (this is normally not used since all resources are/should be
      // returned when the script terminates
      function Destroy() {
          imagedestroy($this->img);
      }
  
      // Specify image format. Note depending on your installation
      // of PHP not all formats may be supported.
      function SetImgFormat($aFormat,$aQuality=75) {
          $this->quality = $aQuality;
          $aFormat = strtolower($aFormat);
          $tst = true;
          $supported = imagetypes();
          if( $aFormat=="auto" ) {
              if( $supported & IMG_PNG )      $this->img_format="png";
              elseif( $supported & IMG_JPG )  $this->img_format="jpeg";
              elseif( $supported & IMG_GIF )  $this->img_format="gif";
              elseif( $supported & IMG_WBMP ) $this->img_format="wbmp";
              elseif( $supported & IMG_XPM )  $this->img_format="xpm";
              else {
                  JpGraphError::RaiseL(25109);//("Your PHP (and GD-lib) installation does not appear to support any known graphic formats. You need to first make sure GD is compiled as a module to PHP. If you also want to use JPEG images you must get the JPEG library. Please see the PHP docs for details.");
              }
              return true;
          }
          else {
              if( $aFormat=="jpeg" || $aFormat=="png" || $aFormat=="gif" ) {
                  if( $aFormat=="jpeg" && !($supported & IMG_JPG) )       $tst=false;
                  elseif( $aFormat=="png" && !($supported & IMG_PNG) )    $tst=false;
                  elseif( $aFormat=="gif" && !($supported & IMG_GIF) )    $tst=false;
                  elseif( $aFormat=="wbmp" && !($supported & IMG_WBMP) )  $tst=false;
                  elseif( $aFormat=="xpm" && !($supported & IMG_XPM) )    $tst=false;
                  else {
                      $this->img_format=$aFormat;
                      return true;
                  }
              }
              else {
                  $tst=false;
              }
              if( !$tst ) {
                  JpGraphError::RaiseL(25110,$aFormat);//(" Your PHP installation does not support the chosen graphic format: $aFormat");
              }
          }
      }
  
      /**
      * Draw Line
      */
      function DrawLine($im, $x1, $y1, $x2, $y2, $weight, $color) {
          if ($weight == 1) {
              return imageline($im,$x1,$y1,$x2,$y2,$color);
          }
  
          $angle=(atan2(($y1 - $y2), ($x2 - $x1))); 
  
          $dist_x = $weight * (sin($angle)) / 2;
          $dist_y = $weight * (cos($angle)) / 2;
          
          $p1x=ceil(($x1 + $dist_x));
          $p1y=ceil(($y1 + $dist_y));
          $p2x=ceil(($x2 + $dist_x));
          $p2y=ceil(($y2 + $dist_y));
          $p3x=ceil(($x2 - $dist_x));
          $p3y=ceil(($y2 - $dist_y));
          $p4x=ceil(($x1 - $dist_x));
          $p4y=ceil(($y1 - $dist_y));
  
          $array=array($p1x,$p1y,$p2x,$p2y,$p3x,$p3y,$p4x,$p4y);
          imagefilledpolygon ( $im, $array, (count($array)/2), $color );
  
          // for antialias
          imageline($im, $p1x, $p1y, $p2x, $p2y, $color);
          imageline($im, $p3x, $p3y, $p4x, $p4y, $color);
          return;
  
  
  
            return imageline($this->img,$x1,$y1,$x2,$y2,$this->current_color);
        $weight = 8;
          if ($weight <= 1) {
            return imageline($this->img,$x1,$y1,$x2,$y2,$this->current_color);
          }
  
          $pts = array();
  
          $weight /= 2;
  
          if ($y2 - $y1 == 0) {
              // x line
              $pts = array();
              $pts[] = $x1; $pts[] = $y1 - $weight;
              $pts[] = $x1; $pts[] = $y1 + $weight;
              $pts[] = $x2; $pts[] = $y2 + $weight;
              $pts[] = $x2; $pts[] = $y2 - $weight;
  
          } elseif ($x2 - $x1 == 0) {
              // y line
              $pts = array();
              $pts[] = $x1 - $weight; $pts[] = $y1;
              $pts[] = $x1 + $weight; $pts[] = $y1;
              $pts[] = $x2 + $weight; $pts[] = $y2;
              $pts[] = $x2 - $weight; $pts[] = $y2;
  
          } else {
              
              var_dump($x1, $x2, $y1, $y2);
              $length = sqrt(pow($x2 - $x1, 2) + pow($y2 - $y1, 2));
              var_dump($length);exit;
              exit;
    
  /*
              $lean = ($y2 - $y1) / ($x2 - $x1);
              $lean2 = -1 / $lean;
              $sin = $lean / ($y2 - $y1);
              $cos = $lean / ($x2 - $x1);
  
              $pts[] = $x1 + (-$weight * $sin); $pts[] = $y1 + (-$weight * $cos);
              $pts[] = $x1 + (+$weight * $sin); $pts[] = $y1 + (+$weight * $cos);
              $pts[] = $x2 + (+$weight * $sin); $pts[] = $y2 + (+$weight * $cos);
              $pts[] = $x2 + (-$weight * $sin); $pts[] = $y2 + (-$weight * $cos);
  */
          }
  
  //print_r($pts);exit;
          if (count($pts)/2 < 3) {
              return;
          } 
  
          imagesetthickness($im, 1);
          imagefilledpolygon($im, $pts,count($pts)/2, $color);
  
  
          $weight *= 2;
  
  //        $this->DrawImageSmoothArc($im, $x1, $y1, $weight, $weight, 0, 360, $color);
  //        $this->DrawImageSmoothArc($im, $x2, $y2, $weight, $weight, 0, 360, $color);
      }
  
  
      function DrawImageSmoothArc($im, $xc, $yc, $w, $h, $s, $e, $color, $style = null) {
          $tmp = $s;
          $s = (360 - $e) / 180 * M_PI;
          $e = (360 - $tmp) / 180 * M_PI;
          return imageSmoothArc($im, round($xc), round($yc), round($w), round($h), $this->CreateColorForImageSmoothArc($color), $s, $e);
      }
  
      function CreateColorForImageSmoothArc($color) {
          $alpha = $color >> 24 & 0xFF; 
          $red   = $color >> 16 & 0xFF;
          $green = $color >> 8 & 0xFF;
          $blue  = $color & 0xFF;
  
  //var_dump($alpha, $red, $green, $blue);exit;
  
          return array($red, $green, $blue, $alpha);
      }
  
      function imageSmoothCircle( &$img, $cx, $cy, $cr, $color ) {
          $ir = $cr;
          $ix = 0;
          $iy = $ir;
          $ig = 2 * $ir - 3;
          $idgr = -6;
          $idgd = 4 * $ir - 10;
          $fill = imageColorExactAlpha( $img, $color[ 'R' ], $color[ 'G' ], $color[ 'B' ], 0 );
          imageLine( $img, $cx + $cr - 1, $cy, $cx, $cy, $fill );
          imageLine( $img, $cx - $cr + 1, $cy, $cx - 1, $cy, $fill );
          imageLine( $img, $cx, $cy + $cr - 1, $cx, $cy + 1, $fill );
          imageLine( $img, $cx, $cy - $cr + 1, $cx, $cy - 1, $fill );
          $draw = imageColorExactAlpha( $img, $color[ 'R' ], $color[ 'G' ], $color[ 'B' ], 42 );
          imageSetPixel( $img, $cx + $cr, $cy, $draw );
          imageSetPixel( $img, $cx - $cr, $cy, $draw );
          imageSetPixel( $img, $cx, $cy + $cr, $draw );
          imageSetPixel( $img, $cx, $cy - $cr, $draw );
          while ( $ix <= $iy - 2 ) {
              if ( $ig < 0 ) {
                  $ig += $idgd;
                  $idgd -= 8;
                  $iy--;
              } else {
                  $ig += $idgr;
                  $idgd -= 4;
              }
              $idgr -= 4;
              $ix++;
              imageLine( $img, $cx + $ix, $cy + $iy - 1, $cx + $ix, $cy + $ix, $fill );
              imageLine( $img, $cx + $ix, $cy - $iy + 1, $cx + $ix, $cy - $ix, $fill );
              imageLine( $img, $cx - $ix, $cy + $iy - 1, $cx - $ix, $cy + $ix, $fill );
              imageLine( $img, $cx - $ix, $cy - $iy + 1, $cx - $ix, $cy - $ix, $fill );
              imageLine( $img, $cx + $iy - 1, $cy + $ix, $cx + $ix, $cy + $ix, $fill );
              imageLine( $img, $cx + $iy - 1, $cy - $ix, $cx + $ix, $cy - $ix, $fill );
              imageLine( $img, $cx - $iy + 1, $cy + $ix, $cx - $ix, $cy + $ix, $fill );
              imageLine( $img, $cx - $iy + 1, $cy - $ix, $cx - $ix, $cy - $ix, $fill );
              $filled = 0;
              for ( $xx = $ix - 0.45; $xx < $ix + 0.5; $xx += 0.2 ) {
                  for ( $yy = $iy - 0.45; $yy < $iy + 0.5; $yy += 0.2 ) {
                      if ( sqrt( pow( $xx, 2 ) + pow( $yy, 2 ) ) < $cr ) $filled += 4;
                  }
              }
              $draw = imageColorExactAlpha( $img, $color[ 'R' ], $color[ 'G' ], $color[ 'B' ], ( 100 - $filled ) );
              imageSetPixel( $img, $cx + $ix, $cy + $iy, $draw );
              imageSetPixel( $img, $cx + $ix, $cy - $iy, $draw );
              imageSetPixel( $img, $cx - $ix, $cy + $iy, $draw );
              imageSetPixel( $img, $cx - $ix, $cy - $iy, $draw );
              imageSetPixel( $img, $cx + $iy, $cy + $ix, $draw );
              imageSetPixel( $img, $cx + $iy, $cy - $ix, $draw );
              imageSetPixel( $img, $cx - $iy, $cy + $ix, $draw );
              imageSetPixel( $img, $cx - $iy, $cy - $ix, $draw );
          }
      }
  
      function __get($name) {
  
          if (strpos($name, 'raw_') !== false) {
              // if $name == 'raw_left_margin' , return $this->_left_margin;
              $variable_name = '_' . str_replace('raw_', '', $name);
              return $this->$variable_name;
          }
  
          $variable_name = '_' . $name; 
  
          if (isset($this->$variable_name)) {
              return $this->$variable_name * SUPERSAMPLING_SCALE;
          } else {
              JpGraphError::RaiseL('25132', $name);
          } 
      }
  
      function __set($name, $value) {
          $this->{'_'.$name} = $value;
      }
  
  } // CLASS
  
  //===================================================
  // CLASS RotImage
  // Description: Exactly as Image but draws the image at
  // a specified angle around a specified rotation point.
  //===================================================
  class RotImage extends Image {
      public $a=0;
      public $dx=0,$dy=0,$transx=0,$transy=0;
      private $m=array();
  
      function __construct($aWidth,$aHeight,$a=0,$aFormat=DEFAULT_GFORMAT,$aSetAutoMargin=true) {
          parent::__construct($aWidth,$aHeight,$aFormat,$aSetAutoMargin);
          $this->dx=$this->width/2;
          $this->dy=$this->height/2;
          $this->SetAngle($a);
      }
  
      function SetCenter($dx,$dy) {
          $old_dx = $this->dx;
          $old_dy = $this->dy;
          $this->dx=$dx;
          $this->dy=$dy;
          $this->SetAngle($this->a);
          return array($old_dx,$old_dy);
      }
  
      function SetTranslation($dx,$dy) {
          $old = array($this->transx,$this->transy);
          $this->transx = $dx;
          $this->transy = $dy;
          return $old;
      }
  
      function UpdateRotMatrice()  {
          $a = $this->a;
          $a *= M_PI/180;
          $sa=sin($a); $ca=cos($a);
          // Create the rotation matrix
          $this->m[0][0] = $ca;
          $this->m[0][1] = -$sa;
          $this->m[0][2] = $this->dx*(1-$ca) + $sa*$this->dy ;
          $this->m[1][0] = $sa;
          $this->m[1][1] = $ca;
          $this->m[1][2] = $this->dy*(1-$ca) - $sa*$this->dx ;
      }
  
      function SetAngle($a) {
          $tmp = $this->a;
          $this->a = $a;
          $this->UpdateRotMatrice();
          return $tmp;
      }
  
      function Circle($xc,$yc,$r) {
          list($xc,$yc) = $this->Rotate($xc,$yc);
          parent::Circle($xc,$yc,$r);
      }
  
      function FilledCircle($xc,$yc,$r) {
          list($xc,$yc) = $this->Rotate($xc,$yc);
          parent::FilledCircle($xc,$yc,$r);
      }
  
  
      function Arc($xc,$yc,$w,$h,$s,$e) {
          list($xc,$yc) = $this->Rotate($xc,$yc);
          $s += $this->a;
          $e += $this->a;
          parent::Arc($xc,$yc,$w,$h,$s,$e);
      }
  
      function FilledArc($xc,$yc,$w,$h,$s,$e,$style='') {
          list($xc,$yc) = $this->Rotate($xc,$yc);
          $s += $this->a;
          $e += $this->a;
          parent::FilledArc($xc,$yc,$w,$h,$s,$e);
      }
  
      function SetMargin($lm,$rm,$tm,$bm) {
          parent::SetMargin($lm,$rm,$tm,$bm);
          $this->UpdateRotMatrice();
      }
  
      function Rotate($x,$y) {
          // Optimization. Ignore rotation if Angle==0 || Angle==360
          if( $this->a == 0 || $this->a == 360 ) {
              return array($x + $this->transx, $y + $this->transy );
          }
          else {
              $x1=round($this->m[0][0]*$x + $this->m[0][1]*$y,1) + $this->m[0][2] + $this->transx;
              $y1=round($this->m[1][0]*$x + $this->m[1][1]*$y,1) + $this->m[1][2] + $this->transy;
              return array($x1,$y1);
          }
      }
  
      function CopyMerge($fromImg,$toX,$toY,$fromX,$fromY,$toWidth,$toHeight,$fromWidth=-1,$fromHeight=-1,$aMix=100) {
          list($toX,$toY) = $this->Rotate($toX,$toY);
          parent::CopyMerge($fromImg,$toX,$toY,$fromX,$fromY,$toWidth,$toHeight,$fromWidth,$fromHeight,$aMix);
  
      }
  
      function ArrRotate($pnts) {
          $n = count($pnts)-1;
          for($i=0; $i < $n; $i+=2) {
              list ($x,$y) = $this->Rotate($pnts[$i],$pnts[$i+1]);
              $pnts[$i] = $x; $pnts[$i+1] = $y;
          }
          return $pnts;
      }
  
      function DashedLine($x1,$y1,$x2,$y2,$dash_length=1,$dash_space=4) {
          list($x1,$y1) = $this->Rotate($x1,$y1);
          list($x2,$y2) = $this->Rotate($x2,$y2);
          parent::DashedLine($x1,$y1,$x2,$y2,$dash_length,$dash_space);
      }
  
      function Line($x1,$y1,$x2,$y2) {
          list($x1,$y1) = $this->Rotate($x1,$y1);
          list($x2,$y2) = $this->Rotate($x2,$y2);
          parent::Line($x1,$y1,$x2,$y2);
      }
  
      function Rectangle($x1,$y1,$x2,$y2) {
          // Rectangle uses Line() so it will be rotated through that call
          parent::Rectangle($x1,$y1,$x2,$y2);
      }
  
      function FilledRectangle($x1,$y1,$x2,$y2) {
          if( $y1==$y2 || $x1==$x2 )
          $this->Line($x1,$y1,$x2,$y2);
          else
          $this->FilledPolygon(array($x1,$y1,$x2,$y1,$x2,$y2,$x1,$y2));
      }
  
      function Polygon($pnts,$closed=FALSE,$fast=FALSE) {
          // Polygon uses Line() so it will be rotated through that call unless
          // fast drawing routines are used in which case a rotate is needed
          if( $fast ) {
              parent::Polygon($this->ArrRotate($pnts));
          }
          else {
              parent::Polygon($pnts,$closed,$fast);
          }
      }
  
      function FilledPolygon($pnts) {
          parent::FilledPolygon($this->ArrRotate($pnts));
      }
  
      function Point($x,$y) {
          list($xp,$yp) = $this->Rotate($x,$y);
          parent::Point($xp,$yp);
      }
  
      function StrokeText($x,$y,$txt,$dir=0,$paragraph_align="left",$debug=false) {
          list($xp,$yp) = $this->Rotate($x,$y);
          return parent::StrokeText($xp,$yp,$txt,$dir,$paragraph_align,$debug);
      }
  }
  
  //=======================================================================
  // CLASS ImgStreamCache
  // Description: Handle caching of graphs to files. All image output goes
  //              through this class
  //=======================================================================
  class ImgStreamCache {
      private $cache_dir, $timeout=0;  // Infinite timeout
      //---------------
      // CONSTRUCTOR
      function __construct($aCacheDir=CACHE_DIR) {
          $this->cache_dir = $aCacheDir;
      }
  
      //---------------
      // PUBLIC METHODS
  
      // Specify a timeout (in minutes) for the file. If the file is older then the
      // timeout value it will be overwritten with a newer version.
      // If timeout is set to 0 this is the same as infinite large timeout and if
      // timeout is set to -1 this is the same as infinite small timeout
      function SetTimeout($aTimeout) {
          $this->timeout=$aTimeout;
      }
  
      // Output image to browser and also write it to the cache
      function PutAndStream($aImage,$aCacheFileName,$aInline,$aStrokeFileName) {
  
          // Check if we should always stroke the image to a file
          if( _FORCE_IMGTOFILE ) {
              $aStrokeFileName = _FORCE_IMGDIR.GenImgName();
          }
  
          if( $aStrokeFileName != '' ) {
  
              if( $aStrokeFileName == 'auto' ) {
                  $aStrokeFileName = GenImgName();
              }
  
              if( file_exists($aStrokeFileName) ) {
  
                  // Wait for lock (to make sure no readers are trying to access the image)
                  $fd = fopen($aStrokeFileName,'w');
                  $lock = flock($fd, LOCK_EX);
  
                  // Since the image write routines only accepts a filename which must not
                  // exist we need to delete the old file first
                  if( !@unlink($aStrokeFileName) ) {
                      $lock = flock($fd, LOCK_UN);
                      JpGraphError::RaiseL(25111,$aStrokeFileName);
                      //(" Can't delete cached image $aStrokeFileName. Permission problem?");
                  }
                  $aImage->Stream($aStrokeFileName);
                  $lock = flock($fd, LOCK_UN);
                  fclose($fd);
  
              }
              else {
                  $aImage->Stream($aStrokeFileName);
              }
  
              return;
          }
  
          if( $aCacheFileName != '' && USE_CACHE) {
  
              $aCacheFileName = $this->cache_dir . $aCacheFileName;
              if( file_exists($aCacheFileName) ) {
                  if( !$aInline ) {
                      // If we are generating image off-line (just writing to the cache)
                      // and the file exists and is still valid (no timeout)
                      // then do nothing, just return.
                      $diff=time()-filemtime($aCacheFileName);
                      if( $diff < 0 ) {
                          JpGraphError::RaiseL(25112,$aCacheFileName);
                          //(" Cached imagefile ($aCacheFileName) has file date in the future!!");
                      }
                      if( $this->timeout>0 && ($diff <= $this->timeout*60) ) return;
                  }
  
                  // Wait for lock (to make sure no readers are trying to access the image)
                  $fd = fopen($aCacheFileName,'w');
                  $lock = flock($fd, LOCK_EX);
  
                  if( !@unlink($aCacheFileName) ) {
                      $lock = flock($fd, LOCK_UN);
                      JpGraphError::RaiseL(25113,$aStrokeFileName);
                      //(" Can't delete cached image $aStrokeFileName. Permission problem?");
                  }
                  $aImage->Stream($aCacheFileName);
                  $lock = flock($fd, LOCK_UN);
                  fclose($fd);
  
              }
              else {
                  $this->MakeDirs(dirname($aCacheFileName));
                  if( !is_writeable(dirname($aCacheFileName)) ) {
                      JpGraphError::RaiseL(25114,$aCacheFileName);
                      //('PHP has not enough permissions to write to the cache file '.$aCacheFileName.'. Please make sure that the user running PHP has write permission for this file if you wan to use the cache system with JpGraph.');
                  }
                  $aImage->Stream($aCacheFileName);
              }
  
              $res=true;
              // Set group to specified
              if( CACHE_FILE_GROUP != '' ) {
                  $res = @chgrp($aCacheFileName,CACHE_FILE_GROUP);
              }
              if( CACHE_FILE_MOD != '' ) {
                  $res = @chmod($aCacheFileName,CACHE_FILE_MOD);
              }
              if( !$res ) {
                  JpGraphError::RaiseL(25115,$aStrokeFileName);
                  //(" Can't set permission for cached image $aStrokeFileName. Permission problem?");
              }
  
              $aImage->Destroy();
              if( $aInline ) {
                  if ($fh = @fopen($aCacheFileName, "rb") ) {
                      $aImage->Headers();
                      fpassthru($fh);
                      return;
                  }
                  else {
                      JpGraphError::RaiseL(25116,$aFile);//(" Cant open file from cache [$aFile]");
                  }
              }
          }
          elseif( $aInline ) {
              $aImage->Headers();
              $aImage->Stream();
              return;
          }
      }
  
      function IsValid($aCacheFileName) {
          $aCacheFileName = $this->cache_dir.$aCacheFileName;
          if ( USE_CACHE && file_exists($aCacheFileName) ) {
              $diff=time()-filemtime($aCacheFileName);
              if( $this->timeout>0 && ($diff > $this->timeout*60) ) {
                  return false;
              }
              else {
                  return true;
              }
          }
          else {
              return false;
          }
      }
  
      function StreamImgFile($aImage,$aCacheFileName) {
          $aCacheFileName = $this->cache_dir.$aCacheFileName;
          if ( $fh = @fopen($aCacheFileName, 'rb') ) {
              $lock = flock($fh, LOCK_SH);
              $aImage->Headers();
              fpassthru($fh);
              $lock = flock($fh, LOCK_UN);
              fclose($fh);
              return true;
          }
          else {
              JpGraphError::RaiseL(25117,$aCacheFileName);//(" Can't open cached image \"$aCacheFileName\" for reading.");
          }
      }
  
      // Check if a given image is in cache and in that case
      // pass it directly on to web browser. Return false if the
      // image file doesn't exist or exists but is to old
      function GetAndStream($aImage,$aCacheFileName) {
          if( $this->Isvalid($aCacheFileName) ) {
              $this->StreamImgFile($aImage,$aCacheFileName);
          }
          else {
              return false;
          }
      }
  
      //---------------
      // PRIVATE METHODS
      // Create all necessary directories in a path
      function MakeDirs($aFile) {
          $dirs = array();
          // In order to better work when open_basedir is enabled
          // we do not create directories in the root path
          while ( $aFile != '/' && !(file_exists($aFile)) ) {
              $dirs[] = $aFile.'/';
              $aFile = dirname($aFile);
          }
          for ($i = sizeof($dirs)-1; $i>=0; $i--) {
              if(! @mkdir($dirs[$i],0777) ) {
                  JpGraphError::RaiseL(25118,$aFile);//(" Can't create directory $aFile. Make sure PHP has write permission to this directory.");
              }
              // We also specify mode here after we have changed group.
              // This is necessary if Apache user doesn't belong the
              // default group and hence can't specify group permission
              // in the previous mkdir() call
              if( CACHE_FILE_GROUP != "" ) {
                  $res=true;
                  $res =@chgrp($dirs[$i],CACHE_FILE_GROUP);
                  $res = @chmod($dirs[$i],0777);
                  if( !$res ) {
                      JpGraphError::RaiseL(25119,$aFile);//(" Can't set permissions for $aFile. Permission problems?");
                  }
              }
          }
          return true;
      }
  } // CLASS Cache
  
  ?>