ryzom /code/ryzom/tools/server/admin/jpgraph/jpgraph.php

Language PHP Lines 8564
MD5 Hash cf2757885786d4194abb37ba5582567a Estimated Cost $191,097 (why?)
Repository https://bitbucket.org/SirCotare/ryzom View Raw File View Project SPDX
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
<?php
//=======================================================================
// File:	JPGRAPH.PHP
// Description:	PHP Graph Plotting library. Base module.
// Created: 	2001-01-08
// Author:	Johan Persson (johanp@aditus.nu)
// Ver:		$Id: jpgraph.php,v 1.1 2006/07/07 13:37:14 powles Exp $
//
// Copyright (c) Aditus Consulting. All rights reserved.
//========================================================================

require_once('jpg-config.inc');

// Version info
DEFINE('JPG_VERSION','1.20.3');

// For internal use only
DEFINE("_JPG_DEBUG",false);
DEFINE("_FORCE_IMGTOFILE",false);
DEFINE("_FORCE_IMGDIR",'/tmp/jpgimg/');


//------------------------------------------------------------------------
// Automatic settings of path for cache and font directory
// if they have not been previously specified
//------------------------------------------------------------------------
if(USE_CACHE) {
    if (!defined('CACHE_DIR')) {
	if ( strstr( PHP_OS, 'WIN') ) {
	    if( empty($_SERVER['TEMP']) ) {
		$t = new ErrMsgText();
		$msg = $t->Get(11,$file,$lineno);
		die($msg);
	    }
	    else {
		DEFINE('CACHE_DIR', $_SERVER['TEMP'] . '/');
	    }
	} else {
	    DEFINE('CACHE_DIR','/tmp/jpgraph_cache/');
	}
    }
}
elseif( !defined('CACHE_DIR') ) {
    DEFINE('CACHE_DIR', '');
}

if (!defined('TTF_DIR')) {
    if (strstr( PHP_OS, 'WIN') ) {
	$sroot = getenv('SystemRoot');
        if( empty($sroot) ) {
	    $t = new ErrMsgText();
	    $msg = $t->Get(12,$file,$lineno);
	    die($msg);
        }
	else {
	  DEFINE('TTF_DIR', $sroot.'/fonts/');
        }
    } else {
	DEFINE('TTF_DIR','/usr/X11R6/lib/X11/fonts/truetype/');
    }
}

//------------------------------------------------------------------
// Constants which are used as parameters for the method calls
//------------------------------------------------------------------

// TTF Font families
DEFINE("FF_COURIER",10);
DEFINE("FF_VERDANA",11);
DEFINE("FF_TIMES",12);
DEFINE("FF_COMIC",14);
DEFINE("FF_ARIAL",15);
DEFINE("FF_GEORGIA",16);
DEFINE("FF_TREBUCHE",17);

// Gnome Vera font
// Available from http://www.gnome.org/fonts/
DEFINE("FF_VERA",19);
DEFINE("FF_VERAMONO",20);
DEFINE("FF_VERASERIF",21);

// Chinese font
DEFINE("FF_SIMSUN",30);
DEFINE("FF_CHINESE",31);
DEFINE("FF_BIG5",31);

// Japanese font
DEFINE("FF_MINCHO",40);
DEFINE("FF_PMINCHO",41);
DEFINE("FF_GOTHIC",42);
DEFINE("FF_PGOTHIC",43);

// Limits for TTF fonts
DEFINE('_FF_FIRST',10);
DEFINE('_FF_LAST',43);

// Older deprecated fonts 
DEFINE("FF_BOOK",91);    // Deprecated fonts from 1.9
DEFINE("FF_HANDWRT",92); // Deprecated fonts from 1.9

// TTF Font styles
DEFINE("FS_NORMAL",9001);
DEFINE("FS_BOLD",9002);
DEFINE("FS_ITALIC",9003);
DEFINE("FS_BOLDIT",9004);
DEFINE("FS_BOLDITALIC",9004);

//Definitions for internal font, new style
DEFINE("FF_FONT0",1);
DEFINE("FF_FONT1",2);
DEFINE("FF_FONT2",4);

// Tick density
DEFINE("TICKD_DENSE",1);
DEFINE("TICKD_NORMAL",2);
DEFINE("TICKD_SPARSE",3);
DEFINE("TICKD_VERYSPARSE",4);

// Side for ticks and labels. 
DEFINE("SIDE_LEFT",-1);
DEFINE("SIDE_RIGHT",1);
DEFINE("SIDE_DOWN",-1);
DEFINE("SIDE_BOTTOM",-1);
DEFINE("SIDE_UP",1);
DEFINE("SIDE_TOP",1);

// Legend type stacked vertical or horizontal
DEFINE("LEGEND_VERT",0);
DEFINE("LEGEND_HOR",1);

// Mark types for plot marks
DEFINE("MARK_SQUARE",1);
DEFINE("MARK_UTRIANGLE",2);
DEFINE("MARK_DTRIANGLE",3);
DEFINE("MARK_DIAMOND",4);
DEFINE("MARK_CIRCLE",5);
DEFINE("MARK_FILLEDCIRCLE",6);
DEFINE("MARK_CROSS",7);
DEFINE("MARK_STAR",8);
DEFINE("MARK_X",9);
DEFINE("MARK_LEFTTRIANGLE",10);
DEFINE("MARK_RIGHTTRIANGLE",11);
DEFINE("MARK_FLASH",12);
DEFINE("MARK_IMG",13);
DEFINE("MARK_FLAG1",14);
DEFINE("MARK_FLAG2",15);
DEFINE("MARK_FLAG3",16);
DEFINE("MARK_FLAG4",17);

// Builtin images
DEFINE("MARK_IMG_PUSHPIN",50);
DEFINE("MARK_IMG_SPUSHPIN",50);
DEFINE("MARK_IMG_LPUSHPIN",51);
DEFINE("MARK_IMG_DIAMOND",52);
DEFINE("MARK_IMG_SQUARE",53);
DEFINE("MARK_IMG_STAR",54);
DEFINE("MARK_IMG_BALL",55);
DEFINE("MARK_IMG_SBALL",55);
DEFINE("MARK_IMG_MBALL",56);
DEFINE("MARK_IMG_LBALL",57);
DEFINE("MARK_IMG_BEVEL",58);

// Inline defines
DEFINE("INLINE_YES",1);
DEFINE("INLINE_NO",0);

// Format for background images
DEFINE("BGIMG_FILLPLOT",1);
DEFINE("BGIMG_FILLFRAME",2);
DEFINE("BGIMG_COPY",3);
DEFINE("BGIMG_CENTER",4);

// Depth of objects
DEFINE("DEPTH_BACK",0);
DEFINE("DEPTH_FRONT",1);

// Direction
DEFINE("VERTICAL",1);
DEFINE("HORIZONTAL",0);


// Axis styles for scientific style axis
DEFINE('AXSTYLE_SIMPLE',1);
DEFINE('AXSTYLE_BOXIN',2);
DEFINE('AXSTYLE_BOXOUT',3);
DEFINE('AXSTYLE_YBOXIN',4);
DEFINE('AXSTYLE_YBOXOUT',5);

// Style for title backgrounds
DEFINE('TITLEBKG_STYLE1',1);
DEFINE('TITLEBKG_STYLE2',2);
DEFINE('TITLEBKG_STYLE3',3);
DEFINE('TITLEBKG_FRAME_NONE',0);
DEFINE('TITLEBKG_FRAME_FULL',1);
DEFINE('TITLEBKG_FRAME_BOTTOM',2);
DEFINE('TITLEBKG_FRAME_BEVEL',3);
DEFINE('TITLEBKG_FILLSTYLE_HSTRIPED',1);
DEFINE('TITLEBKG_FILLSTYLE_VSTRIPED',2);
DEFINE('TITLEBKG_FILLSTYLE_SOLID',3);

// Style for background gradient fills
DEFINE('BGRAD_FRAME',1);
DEFINE('BGRAD_MARGIN',2);
DEFINE('BGRAD_PLOT',3);

// Width of tab titles
DEFINE('TABTITLE_WIDTHFIT',0);
DEFINE('TABTITLE_WIDTHFULL',-1);

// Defines for 3D skew directions
DEFINE('SKEW3D_UP',0);
DEFINE('SKEW3D_DOWN',1);
DEFINE('SKEW3D_LEFT',2);
DEFINE('SKEW3D_RIGHT',3);



//
// Get hold of gradient class (In Version 2.x)
// A client of the library has to manually include this
//
require_once 'jpgraph_gradient.php';


class ErrMsgText {
    var $lt=NULL;
    var $supportedLocales = array('en');
    function ErrMsgText() {
	GLOBAL $__jpg_err_locale;
	if( !in_array($__jpg_err_locale,$this->supportedLocales) )
	    $aLoc = 'en';
	require_once('lang/'.$__jpg_err_locale.'.inc.php');
	$this->lt = $_jpg_messages;
    }

    function Get($errnbr,$a1=null,$a2=null,$a3=null,$a4=null,$a5=null) {
	if( !isset($this->lt[$errnbr]) ) {
	    return 'Internal error: The specified error message does not exist in the chosen locale. (Please blame the translator...))';
	}
	$ea = $this->lt[$errnbr];
	$j=0;
	if( $a1 !== null ) {
	    $argv[$j++] = $a1;
	    if( $a2 !== null ) {
		$argv[$j++] = $a2;
		if( $a3 !== null ) {
		    $argv[$j++] = $a3;
		    if( $a4 !== null ) {
			$argv[$j++] = $a4;
			if( $a5 !== null ) {
			    $argv[$j++] = $a5;
			}
		    }
		}
	    }
	}
	$numargs = $j; 
	if( $ea[1] != $numargs ) {
	    // Error message argument count do not match.
	    // Just return the error message without arguments.
	    return $ea[0];
	}
	switch( $numargs ) {
	    case 1:
		$msg = sprintf($ea[0],$argv[0]);
		break;
	    case 2:
		$msg = sprintf($ea[0],$argv[0],$argv[1]);
		break;
	    case 3:
		$msg = sprintf($ea[0],$argv[0],$argv[1],$argv[2]);
		break;
	    case 4:
		$msg = sprintf($ea[0],$argv[0],$argv[1],$argv[2],$argv[3]);
		break;
	    case 5:
		$msg = sprintf($ea[0],$argv[0],$argv[1],$argv[2],$argv[3],$argv[4]);
		break;
	    case 0:
	    default:
		$msg = sprintf($ea[0]);
		break;
	}
	return $msg;
    }
}

//
// A wrapper class that is used to access the specified error object
// (to hide the global error parameter and avoid having a GLOBAL directive
// in all methods.
//
GLOBAL $__jpg_err;
GLOBAL $__jpg_err_locale ;
$__jpg_err_locale = 'en';
class JpGraphError {
    function Install($aErrObject) {
	GLOBAL $__jpg_err;
	$__jpg_err = $aErrObject;
    }
    function Raise($aMsg,$aHalt=true){
	GLOBAL $__jpg_err;
	$tmp = new $__jpg_err;
	$tmp->Raise($aMsg,$aHalt);
    }
    function RaiseL($errnbr,$a1=null,$a2=null,$a3=null,$a4=null,$a5=null) {
	GLOBAL $__jpg_err;
	$t = new ErrMsgText();
	$msg = $t->Get($errnbr,$a1,$a2,$a3,$a4,$a5);
	$tmp = new $__jpg_err;
	$tmp->Raise($msg);
    }
}
 
//
// ... and install the default error handler
//
if( USE_IMAGE_ERROR_HANDLER ) {
    $__jpg_err = "JpGraphErrObjectImg";
}
else {
    $__jpg_err = "JpGraphErrObject"; 
}

//
// Make GD sanity check
//
if( !function_exists("imagetypes") || !function_exists('imagecreatefromstring') ) {
    JpGraphError::RaiseL(25001);
//("This PHP installation is not configured with the GD library. Please recompile PHP with GD support to run JpGraph. (Neither function imagetypes() nor imagecreatefromstring() does exist)");
}

//
// Routine to determine if GD1 or GD2 is installed
//
function CheckGDVersion() {
    $GDfuncList = get_extension_funcs('gd');
    if( !$GDfuncList ) return 0 ;
    else {
	if( in_array('imagegd2',$GDfuncList) && 
	    in_array('imagecreatetruecolor',$GDfuncList))
	    return 2;
	else
	    return 1;
    } 
}

//
// Check what version of the GD library is installed.
//
$GLOBALS['gd2'] = false;
if( USE_LIBRARY_GD2 === 'auto' ) {
    $gdversion = CheckGDVersion();
    if( $gdversion == 2 ) {
	$GLOBALS['gd2'] = true;
	$GLOBALS['copyfunc'] = 'imagecopyresampled';
    }
    elseif( $gdversion == 1 ) {
	$GLOBALS['gd2'] = false;
	$GLOBALS['copyfunc'] = 'imagecopyresized';
    }
    else {
	JpGraphError::RaiseL(25002);
//(" Your PHP installation does not seem to have the required GD library. Please see the PHP documentation on how to install and enable the GD library.");
    }
}
else {
    $GLOBALS['gd2'] = USE_LIBRARY_GD2;
    $GLOBALS['copyfunc'] = USE_LIBRARY_GD2 ? 'imagecopyresampled' : 'imagecopyresized';
}


//
// First of all set up a default error handler
//


//=============================================================
// The default trivial text error handler.
//=============================================================
class JpGraphErrObject {

    var $iTitle = "JpGraph Error";
    var $iDest = false;

    function JpGraphErrObject() {
	// Empty. Reserved for future use
    }

    function SetTitle($aTitle) {
	$this->iTitle = $aTitle;
    }

    function SetStrokeDest($aDest) { 
	$this->iDest = $aDest; 
    }

    // If aHalt is true then execution can't continue. Typical used for fatal errors.
    function Raise($aMsg,$aHalt=true) {
	$aMsg = $this->iTitle.' '.$aMsg;
	if ($this->iDest) {
	    $f = @fopen($this->iDest,'a');
	    if( $f ) {
		@fwrite($f,$aMsg);
		@fclose($f);
	    }
	}
	else {
	    echo $aMsg;
	}
	if( $aHalt )
	    die();
    }
}

//==============================================================
// An image based error handler
//==============================================================
class JpGraphErrObjectImg extends JpGraphErrObject {

    function Raise($aMsg,$aHalt=true) {
	$img_iconerror = 
	    'iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAMAAAC7IEhfAAAAaV'.
	    'BMVEX//////2Xy8mLl5V/Z2VvMzFi/v1WyslKlpU+ZmUyMjEh/'.
	    'f0VyckJlZT9YWDxMTDjAwMDy8sLl5bnY2K/MzKW/v5yyspKlpY'.
	    'iYmH+MjHY/PzV/f2xycmJlZVlZWU9MTEXY2Ms/PzwyMjLFTjea'.
	    'AAAAAXRSTlMAQObYZgAAAAFiS0dEAIgFHUgAAAAJcEhZcwAACx'.
	    'IAAAsSAdLdfvwAAAAHdElNRQfTBgISOCqusfs5AAABLUlEQVR4'.
	    '2tWV3XKCMBBGWfkranCIVClKLd/7P2Q3QsgCxjDTq+6FE2cPH+'.
	    'xJ0Ogn2lQbsT+Wrs+buAZAV4W5T6Bs0YXBBwpKgEuIu+JERAX6'.
	    'wM2rHjmDdEITmsQEEmWADgZm6rAjhXsoMGY9B/NZBwJzBvn+e3'.
	    'wHntCAJdGu9SviwIwoZVDxPB9+Rc0TSEbQr0j3SA1gwdSn6Db0'.
	    '6Tm1KfV6yzWGQO7zdpvyKLKBDmRFjzeB3LYgK7r6A/noDAfjtS'.
	    'IXaIzbJSv6WgUebTMV4EoRB8a2mQiQjgtF91HdKDKZ1gtFtQjk'.
	    'YcWaR5OKOhkYt+ZsTFdJRfPAApOpQYJTNHvCRSJR6SJngQadfc'.
	    'vd69OLMddVOPCGVnmrFD8bVYd3JXfxXPtLR/+mtv59/ALWiiMx'.
	    'qL72fwAAAABJRU5ErkJggg==' ;

	if( function_exists("imagetypes") )
	    $supported = imagetypes();
	else
	    $supported = 0;

	if( !function_exists('imagecreatefromstring') )
	    $supported = 0;

	if( ob_get_length() || headers_sent() || !($supported & IMG_PNG) ) {
	    // Special case for headers already sent or that the installation doesn't support
	    // the PNG format (which the error icon is encoded in). 
	    // Dont return an image since it can't be displayed
	    die($this->iTitle.' '.$aMsg);		
	}

	$aMsg = wordwrap($aMsg,55);
	$lines = substr_count($aMsg,"\n");

	// Create the error icon GD
	$erricon = Image::CreateFromString(base64_decode($img_iconerror));   

	// Create an image that contains the error text.
	$w=400; 	
	$h=100 + 15*max(0,$lines-3);

	$img = new Image($w,$h);

	// Drop shadow
	$img->SetColor("gray");
	$img->FilledRectangle(5,5,$w-1,$h-1,10);
	$img->SetColor("gray:0.7");
	$img->FilledRectangle(5,5,$w-3,$h-3,10);
	
	// Window background
	$img->SetColor("lightblue");
	$img->FilledRectangle(1,1,$w-5,$h-5);
	$img->CopyCanvasH($img->img,$erricon,5,30,0,0,40,40);

	// Window border
	$img->SetColor("black");
	$img->Rectangle(1,1,$w-5,$h-5);
	$img->Rectangle(0,0,$w-4,$h-4);
	
	// Window top row
	$img->SetColor("darkred");
	for($y=3; $y < 18; $y += 2 ) 
	    $img->Line(1,$y,$w-6,$y);

	// "White shadow"
	$img->SetColor("white");

	// Left window edge
	$img->Line(2,2,2,$h-5);
	$img->Line(2,2,$w-6,2);

	// "Gray button shadow"
	$img->SetColor("darkgray");

	// Gray window shadow
	$img->Line(2,$h-6,$w-5,$h-6);
	$img->Line(3,$h-7,$w-5,$h-7);

	// Window title
	$m = floor($w/2-5);
	$l = 100;
	$img->SetColor("lightgray:1.3");
	$img->FilledRectangle($m-$l,2,$m+$l,16);

	// Stroke text
	$img->SetColor("darkred");
	$img->SetFont(FF_FONT2,FS_BOLD);
	$img->StrokeText($m-50,15,$this->iTitle);
	$img->SetColor("black");
	$img->SetFont(FF_FONT1,FS_NORMAL);
	$txt = new Text($aMsg,52,25);
	$txt->Align("left","top");
	$txt->Stroke($img);
	if ($this->iDest) {
           $img->Stream($this->iDest);
	} else {
	    $img->Headers();
	    $img->Stream();
	}
	if( $aHalt )
	    die();
    }
}

//
// Setup PHP error handler
//
function _phpErrorHandler($errno,$errmsg,$filename, $linenum, $vars) {
    // Respect current error level
    if( $errno & error_reporting() ) {
	JpGraphError::RaiseL(25003,basename($filename),$linenum,$errmsg); 
    }
}

if( INSTALL_PHP_ERR_HANDLER ) {
    set_error_handler("_phpErrorHandler");
}

//
//Check if there were any warnings, perhaps some wrong includes by the user
//
if( isset($GLOBALS['php_errormsg']) && CATCH_PHPERRMSG && 
    !preg_match('|Deprecated|', $GLOBALS['php_errormsg'])) {
    JpGraphError::RaiseL(25004,$GLOBALS['php_errormsg']);
}


// Useful mathematical function
function sign($a) {return $a >= 0 ? 1 : -1;}

// Utility function to generate an image name based on the filename we
// are running from and assuming we use auto detection of graphic format
// (top level), i.e it is safe to call this function
// from a script that uses JpGraph
function GenImgName() {
    global $_SERVER;

    // Determine what format we should use when we save the images
    $supported = imagetypes();
    if( $supported & IMG_PNG )	   $img_format="png";
    elseif( $supported & IMG_GIF ) $img_format="gif";
    elseif( $supported & IMG_JPG ) $img_format="jpeg";

    if( !isset($_SERVER['PHP_SELF']) )
	JpGraphError::RaiseL(25005);
//(" Can't access PHP_SELF, PHP global variable. You can't run PHP from command line if you want to use the 'auto' naming of cache or image files.");
    $fname = basename($_SERVER['PHP_SELF']);
    if( !empty($_SERVER['QUERY_STRING']) ) {
	$q = @$_SERVER['QUERY_STRING'];
	$fname .= '?'.preg_replace("/\W/", "_", $q).'.'.$img_format;
    }
    else {
	$fname = substr($fname,0,strlen($fname)-4).'.'.$img_format;
    }
    return $fname;
}

class LanguageConv {
    var $g2312 = null ;

    function Convert($aTxt,$aFF) {
	if( LANGUAGE_CYRILLIC ) {
	    if( CYRILLIC_FROM_WINDOWS ) {
		$aTxt = convert_cyr_string($aTxt, "w", "k"); 
	    }
	    $isostring = convert_cyr_string($aTxt, "k", "i");
	    $unistring = LanguageConv::iso2uni($isostring);
	    return $unistring;
	}
	elseif( $aFF === FF_SIMSUN ) {
	    // Do Chinese conversion
	    if( $this->g2312 == null ) {
		include_once 'jpgraph_gb2312.php' ;
		$this->g2312 = new GB2312toUTF8();
	    }
	    return $this->g2312->gb2utf8($aTxt);
	}
	elseif( $aFF === FF_CHINESE ) {
	    if( !function_exists('iconv') ) {
		JpGraphError::RaiseL(25006);
//('Usage of FF_CHINESE (FF_BIG5) font family requires that your PHP setup has the iconv() function. By default this is not compiled into PHP (needs the "--width-iconv" when configured).');
	    }
	    return iconv('BIG5','UTF-8',$aTxt);
	}
	else 
	    return $aTxt;
    }

    // Translate iso encoding to unicode
    function iso2uni ($isoline){
	$uniline='';
	for ($i=0; $i < strlen($isoline); $i++){
	    $thischar=substr($isoline,$i,1);
	    $charcode=ord($thischar);
	    $uniline.=($charcode>175) ? "&#" . (1040+($charcode-176)). ";" : $thischar;
	}
	return $uniline;
    }
}

//===================================================
// CLASS JpgTimer
// Description: General timing utility class to handle
// time measurement of generating graphs. Multiple
// timers can be started.
//===================================================
class JpgTimer {
    var $start;
    var $idx;	
//---------------
// CONSTRUCTOR
    function JpgTimer() {
	$this->idx=0;
    }

//---------------
// PUBLIC METHODS	

    // Push a new timer start on stack
    function Push() {
	list($ms,$s)=explode(" ",microtime());	
	$this->start[$this->idx++]=floor($ms*1000) + 1000*$s;	
    }

    // Pop the latest timer start and return the diff with the
    // current time
    function Pop() {
	assert($this->idx>0);
	list($ms,$s)=explode(" ",microtime());	
	$etime=floor($ms*1000) + (1000*$s);
	$this->idx--;
	return $etime-$this->start[$this->idx];
    }
} // Class

$gJpgBrandTiming = BRAND_TIMING;
//===================================================
// CLASS DateLocale
// Description: Hold localized text used in dates
//===================================================
class DateLocale {
 
    var $iLocale = 'C'; // environmental locale be used by default

    var $iDayAbb = null;
    var $iShortDay = null;
    var $iShortMonth = null;
    var $iMonthName = null;

//---------------
// CONSTRUCTOR	
    function DateLocale() {
	settype($this->iDayAbb, 'array');
	settype($this->iShortDay, 'array');
	settype($this->iShortMonth, 'array');
	settype($this->iMonthName, 'array');


	$this->Set('C');
    }

//---------------
// PUBLIC METHODS	
    function Set($aLocale) {
	if ( in_array($aLocale, array_keys($this->iDayAbb)) ){ 
	    $this->iLocale = $aLocale;
	    return TRUE;  // already cached nothing else to do!
	}

	$pLocale = setlocale(LC_TIME, 0); // get current locale for LC_TIME
	$res = @setlocale(LC_TIME, $aLocale);
	if ( ! $res ){
	    JpGraphError::RaiseL(25007,$aLocale);
//("You are trying to use the locale ($aLocale) which your PHP installation does not support. Hint: Use '' to indicate the default locale for this geographic region.");
	    return FALSE;
	}
 
	$this->iLocale = $aLocale;

	for ( $i = 0, $ofs = 0 - strftime('%w'); $i < 7; $i++, $ofs++ ){
	    $day = strftime('%a', strtotime("$ofs day"));
	    $day{0} = strtoupper($day{0});
	    $this->iDayAbb[$aLocale][]= $day{0};
	    $this->iShortDay[$aLocale][]= $day;
	}

	for($i=1; $i<=12; ++$i) {
	    list($short ,$full) = explode('|', strftime("%b|%B",strtotime("2001-$i-01")));
	    $this->iShortMonth[$aLocale][] = ucfirst($short);
	    $this->iMonthName [$aLocale][] = ucfirst($full);
	}

	// Return to original locale
	setlocale(LC_TIME, $pLocale);

	return TRUE;
    }


    function GetDayAbb() {
	return $this->iDayAbb[$this->iLocale];
    }
	
    function GetShortDay() {
	return $this->iShortDay[$this->iLocale];
    }

    function GetShortMonth() {
	return $this->iShortMonth[$this->iLocale];
    }
	
    function GetShortMonthName($aNbr) {
	return $this->iShortMonth[$this->iLocale][$aNbr];
    }

    function GetLongMonthName($aNbr) {
	return $this->iMonthName[$this->iLocale][$aNbr];
    }

    function GetMonth() {
	return $this->iMonthName[$this->iLocale];
    }
}

$gDateLocale = new DateLocale();
$gJpgDateLocale = new DateLocale();


//=======================================================
// CLASS Footer
// Description: Encapsulates the footer line in the Graph
//=======================================================
class Footer {
    var $left,$center,$right;
    var $iLeftMargin = 3;
    var $iRightMargin = 3;
    var $iBottomMargin = 3;

    function Footer() {
	$this->left = new Text();
	$this->left->ParagraphAlign('left');
	$this->center = new Text();
	$this->center->ParagraphAlign('center');
	$this->right = new Text();
	$this->right->ParagraphAlign('right');
    }

    function Stroke(&$aImg) {
	$y = $aImg->height - $this->iBottomMargin;
	$x = $this->iLeftMargin;
	$this->left->Align('left','bottom');
	$this->left->Stroke($aImg,$x,$y);

	$x = ($aImg->width - $this->iLeftMargin - $this->iRightMargin)/2;
	$this->center->Align('center','bottom');
	$this->center->Stroke($aImg,$x,$y);

	$x = $aImg->width - $this->iRightMargin;
	$this->right->Align('right','bottom');
	$this->right->Stroke($aImg,$x,$y);
    }
}


//===================================================
// CLASS Graph
// Description: Main class to handle graphs
//===================================================
class Graph {
    var $cache=null;		// Cache object (singleton)
    var $img=null;			// Img object (singleton)
    var $plots=array();	// Array of all plot object in the graph (for Y 1 axis)
    var $y2plots=array();// Array of all plot object in the graph (for Y 2 axis)
    var $ynplots=array();
    var $xscale=null;		// X Scale object (could be instance of LinearScale or LogScale
    var $yscale=null,$y2scale=null, $ynscale=array();
    var $iIcons = array();      // Array of Icons to add to 
    var $cache_name;		// File name to be used for the current graph in the cache directory
    var $xgrid=null;		// X Grid object (linear or logarithmic)
    var $ygrid=null,$y2grid=null; 
    var $doframe=true,$frame_color=array(0,0,0), $frame_weight=1;	// Frame around graph
    var $boxed=false, $box_color=array(0,0,0), $box_weight=1;		// Box around plot area
    var $doshadow=false,$shadow_width=4,$shadow_color=array(102,102,102);	// Shadow for graph
    var $xaxis=null;		// X-axis (instane of Axis class)
    var $yaxis=null, $y2axis=null, $ynaxis=array();	// Y axis (instance of Axis class)
    var $margin_color=array(200,200,200);	// Margin color of graph
    var $plotarea_color=array(255,255,255);	// Plot area color
    var $title,$subtitle,$subsubtitle; 	// Title and subtitle(s) text object
    var $axtype="linlin";		// Type of axis
    var $xtick_factor;			// Factot to determine the maximum number of ticks depending on the plot with
    var $texts=null, $y2texts=null; 	// Text object to ge shown in the graph
    var $lines=null, $y2lines=null;
    var $bands=null, $y2bands=null;
    var $text_scale_off=0, $text_scale_abscenteroff=-1; // Text scale offset in fractions and for centering bars in absolute pixels
    var $background_image="",$background_image_type=-1,$background_image_format="png";
    var $background_image_bright=0,$background_image_contr=0,$background_image_sat=0;
    var $image_bright=0, $image_contr=0, $image_sat=0;
    var $inline;
    var $showcsim=0,$csimcolor="red"; //debug stuff, draw the csim boundaris on the image if <>0
    var $grid_depth=DEPTH_BACK;	// Draw grid under all plots as default
    var $iAxisStyle = AXSTYLE_SIMPLE;
    var $iCSIMdisplay=false,$iHasStroked = false;
    var $footer;
    var $csimcachename = '', $csimcachetimeout = 0;
    var $iDoClipping = false;
    var $y2orderback=true;
    var $tabtitle;
    var $bkg_gradtype=-1,$bkg_gradstyle=BGRAD_MARGIN;
    var $bkg_gradfrom='navy', $bkg_gradto='silver';
    var $titlebackground = false;
    var	$titlebackground_color = 'lightblue',
	$titlebackground_style = 1,
	$titlebackground_framecolor = 'blue',
	$titlebackground_framestyle = 2,
	$titlebackground_frameweight = 1,
	$titlebackground_bevelheight = 3 ;
    var $titlebkg_fillstyle=TITLEBKG_FILLSTYLE_SOLID;
    var $titlebkg_scolor1='black',$titlebkg_scolor2='white';
    var $framebevel = false, $framebeveldepth = 2 ;
    var $framebevelborder = false, $framebevelbordercolor='black';
    var $framebevelcolor1='white@0.4', $framebevelcolor2='black@0.4';
    var $background_image_mix=100;
    var $background_cflag = '';
    var $background_cflag_type = BGIMG_FILLPLOT;
    var $background_cflag_mix = 100;
    var $iImgTrans=false,
	$iImgTransHorizon = 100,$iImgTransSkewDist=150,
	$iImgTransDirection = 1, $iImgTransMinSize = true,
	$iImgTransFillColor='white',$iImgTransHighQ=false,
	$iImgTransBorder=false,$iImgTransHorizonPos=0.5;
    var $iYAxisDeltaPos=50;
    var $iIconDepth=DEPTH_BACK;
    var $iAxisLblBgType = 0,
	$iXAxisLblBgFillColor = 'lightgray', $iXAxisLblBgColor = 'black',
	$iYAxisLblBgFillColor = 'lightgray', $iYAxisLblBgColor = 'black';
    var $iTables=NULL;

//---------------
// CONSTRUCTOR

    // aWIdth 		Width in pixels of image
    // aHeight  	Height in pixels of image
    // aCachedName	Name for image file in cache directory 
    // aTimeOut		Timeout in minutes for image in cache
    // aInline		If true the image is streamed back in the call to Stroke()
    //			If false the image is just created in the cache
    function Graph($aWidth=300,$aHeight=200,$aCachedName="",$aTimeOut=0,$aInline=true) {
	GLOBAL $gJpgBrandTiming;
	// If timing is used create a new timing object
	if( $gJpgBrandTiming ) {
	    global $tim;
	    $tim = new JpgTimer();
	    $tim->Push();
	}

	if( !is_numeric($aWidth) || !is_numeric($aHeight) ) {
	    JpGraphError::RaiseL(25008);//('Image width/height argument in Graph::Graph() must be numeric');
	}
		
	// Automatically generate the image file name based on the name of the script that
	// generates the graph
	if( $aCachedName=="auto" )
	    $aCachedName=GenImgName();
			
	// Should the image be streamed back to the browser or only to the cache?
	$this->inline=$aInline;
		
	$this->img	= new RotImage($aWidth,$aHeight);

	$this->cache 	= new ImgStreamCache($this->img);
	$this->cache->SetTimeOut($aTimeOut);

	$this->title = new Text();
	$this->title->ParagraphAlign('center');
	$this->title->SetFont(FF_FONT2,FS_BOLD);
	$this->title->SetMargin(3);
	$this->title->SetAlign('center');

	$this->subtitle = new Text();
	$this->subtitle->ParagraphAlign('center');
	$this->subtitle->SetMargin(2);
	$this->subtitle->SetAlign('center');

	$this->subsubtitle = new Text();
	$this->subsubtitle->ParagraphAlign('center');
	$this->subsubtitle->SetMargin(2);
	$this->subsubtitle->SetAlign('center');

	$this->legend = new Legend();
	$this->footer = new Footer();

	// Window doesn't like '?' in the file name so replace it with an '_'
	$aCachedName = str_replace("?","_",$aCachedName);

	// If the cached version exist just read it directly from the
	// cache, stream it back to browser and exit
	if( $aCachedName!="" && READ_CACHE && $aInline )
	    if( $this->cache->GetAndStream($aCachedName) ) {
		exit();
	    }
				
	$this->cache_name = $aCachedName;
	$this->SetTickDensity(); // Normal density

	$this->tabtitle = new GraphTabTitle();
    }
//---------------
// PUBLIC METHODS	
    // Enable final image perspective transformation
    function Set3DPerspective($aDir=1,$aHorizon=100,$aSkewDist=120,$aQuality=false,$aFillColor='#FFFFFF',$aBorder=false,$aMinSize=true,$aHorizonPos=0.5) {
	$this->iImgTrans = true;
	$this->iImgTransHorizon = $aHorizon;
	$this->iImgTransSkewDist= $aSkewDist;
	$this->iImgTransDirection = $aDir;
	$this->iImgTransMinSize = $aMinSize;
	$this->iImgTransFillColor=$aFillColor;
	$this->iImgTransHighQ=$aQuality;
	$this->iImgTransBorder=$aBorder;
	$this->iImgTransHorizonPos=$aHorizonPos;
    }

    // Set Image format and optional quality
    function SetImgFormat($aFormat,$aQuality=75) {
	$this->img->SetImgFormat($aFormat,$aQuality);
    }

    // Should the grid be in front or back of the plot?
    function SetGridDepth($aDepth) {
	$this->grid_depth=$aDepth;
    }

    function SetIconDepth($aDepth) {
	$this->iIconDepth=$aDepth;
    }
	
    // Specify graph angle 0-360 degrees.
    function SetAngle($aAngle) {
	$this->img->SetAngle($aAngle);
    }

    function SetAlphaBlending($aFlg=true) {
	$this->img->SetAlphaBlending($aFlg);
    }

    // Shortcut to image margin
    function SetMargin($lm,$rm,$tm,$bm) {
	$this->img->SetMargin($lm,$rm,$tm,$bm);
    }

    function SetY2OrderBack($aBack=true) {
	$this->y2orderback = $aBack;
    }

    // Rotate the graph 90 degrees and set the margin 
    // when we have done a 90 degree rotation
    function Set90AndMargin($lm=0,$rm=0,$tm=0,$bm=0) {
	$lm = $lm ==0 ? floor(0.2 * $this->img->width)  : $lm ;
	$rm = $rm ==0 ? floor(0.1 * $this->img->width)  : $rm ;
	$tm = $tm ==0 ? floor(0.2 * $this->img->height) : $tm ;
	$bm = $bm ==0 ? floor(0.1 * $this->img->height) : $bm ;

	$adj = ($this->img->height - $this->img->width)/2;
	$this->img->SetMargin($tm-$adj,$bm-$adj,$rm+$adj,$lm+$adj);
	$this->img->SetCenter(floor($this->img->width/2),floor($this->img->height/2));
	$this->SetAngle(90);
	if( empty($this->yaxis) || empty($this->xaxis) ) {
	    JpgraphError::RaiseL(25009);//('You must specify what scale to use with a call to Graph::SetScale()');
	}
	$this->xaxis->SetLabelAlign('right','center');
	$this->yaxis->SetLabelAlign('center','bottom');
    }
	
    function SetClipping($aFlg=true) {
	$this->iDoClipping = $aFlg ;
    }

    // Add a plot object to the graph
    function Add(&$aPlot) {
	if( $aPlot == null )
	    JpGraphError::RaiseL(25010);//("Graph::Add() You tried to add a null plot to the graph.");
	if( is_array($aPlot) && count($aPlot) > 0 )
	    $cl = $aPlot[0];
	else
	    $cl = $aPlot;

	if( is_a($cl,'Text') ) 
	    $this->AddText($aPlot);
	elseif( is_a($cl,'PlotLine') )
	    $this->AddLine($aPlot);
	elseif( is_a($cl,'PlotBand') )
	    $this->AddBand($aPlot);
	elseif( is_a($cl,'IconPlot') )
	    $this->AddIcon($aPlot);
	elseif( is_a($cl,'GTextTable') )
	    $this->AddTable($aPlot);
	else
	    $this->plots[] = &$aPlot;
    }


    function AddTable(&$aTable) {
	if( is_array($aTable) ) {
	    for($i=0; $i < count($aTable); ++$i )
		$this->iTables[]=&$aTable[$i];
	}
	else {
	    $this->iTables[] = &$aTable ;
	}	
    }

    function AddIcon(&$aIcon) {
	if( is_array($aIcon) ) {
	    for($i=0; $i < count($aIcon); ++$i )
		$this->iIcons[]=&$aIcon[$i];
	}
	else {
	    $this->iIcons[] = &$aIcon ;
	}	
    }

    // Add plot to second Y-scale
    function AddY2(&$aPlot) {
	if( $aPlot == null )
	    JpGraphError::RaiseL(25011);//("Graph::AddY2() You tried to add a null plot to the graph.");	

	if( is_array($aPlot) && count($aPlot) > 0 )
	    $cl = $aPlot[0];
	else
	    $cl = $aPlot;

	if( is_a($cl,'Text') ) 
	    $this->AddText($aPlot,true);
	elseif( is_a($cl,'PlotLine') )
	    $this->AddLine($aPlot,true);
	elseif( is_a($cl,'PlotBand') )
	    $this->AddBand($aPlot,true);
	else
	    $this->y2plots[] = &$aPlot;
    }

    // Add plot to second Y-scale
    function AddY($aN,&$aPlot) {

	if( $aPlot == null )
	    JpGraphError::RaiseL(25012);//("Graph::AddYN() You tried to add a null plot to the graph.");	

	if( is_array($aPlot) && count($aPlot) > 0 )
	    $cl = $aPlot[0];
	else
	    $cl = $aPlot;

	if( is_a($cl,'Text') || is_a($cl,'PlotLine') || is_a($cl,'PlotBand') )
	    JpGraph::RaiseL(25013);//('You can only add standard plots to multiple Y-axis');
	else
	    $this->ynplots[$aN][] = &$aPlot;
    }
    
    // Add text object to the graph
    function AddText(&$aTxt,$aToY2=false) {
	if( $aTxt == null )
	    JpGraphError::RaiseL(25014);//("Graph::AddText() You tried to add a null text to the graph.");		
	if( $aToY2 ) {
	    if( is_array($aTxt) ) {
		for($i=0; $i < count($aTxt); ++$i )
		    $this->y2texts[]=&$aTxt[$i];
	    }
	    else
		$this->y2texts[] = &$aTxt;
	}
	else {
	    if( is_array($aTxt) ) {
		for($i=0; $i < count($aTxt); ++$i )
		    $this->texts[]=&$aTxt[$i];
	    }
	    else
		$this->texts[] = &$aTxt;
	}
    }
	
    // Add a line object (class PlotLine) to the graph
    function AddLine(&$aLine,$aToY2=false) {
	if( $aLine == null )
	    JpGraphError::RaiseL(25015);//("Graph::AddLine() You tried to add a null line to the graph.");	

	if( $aToY2 ) {
 	    if( is_array($aLine) ) {
		for($i=0; $i < count($aLine); ++$i )
		    $this->y2lines[]=&$aLine[$i];
	    }
	    else
		$this->y2lines[] = &$aLine;
	}
	else {
 	    if( is_array($aLine) ) {
		for($i=0; $i < count($aLine); ++$i )
		    $this->lines[]=&$aLine[$i];
	    }
	    else
		$this->lines[] = &$aLine;
	}
    }

    // Add vertical or horizontal band
    function AddBand(&$aBand,$aToY2=false) {
	if( $aBand == null )
	    JpGraphError::RaiseL(25016);//(" Graph::AddBand() You tried to add a null band to the graph.");

	if( $aToY2 ) {
	    if( is_array($aBand) ) {
		for($i=0; $i < count($aBand); ++$i )
		    $this->y2bands[] = &$aBand[$i];
	    }
	    else
		$this->y2bands[] = &$aBand;
	}
	else {
	    if( is_array($aBand) ) {
		for($i=0; $i < count($aBand); ++$i )
		    $this->bands[] = &$aBand[$i];
	    }
	    else
		$this->bands[] = &$aBand;
	}
    }

    function SetBackgroundGradient($aFrom='navy',$aTo='silver',$aGradType=2,$aStyle=BGRAD_FRAME) {
	$this->bkg_gradtype=$aGradType;
	$this->bkg_gradstyle=$aStyle;
	$this->bkg_gradfrom = $aFrom;
	$this->bkg_gradto = $aTo;
    } 
	
    // Set a country flag in the background
    function SetBackgroundCFlag($aName,$aBgType=BGIMG_FILLPLOT,$aMix=100) {
	$this->background_cflag = $aName;
	$this->background_cflag_type = $aBgType;
	$this->background_cflag_mix = $aMix;
    }

    // Alias for the above method
    function SetBackgroundCountryFlag($aName,$aBgType=BGIMG_FILLPLOT,$aMix=100) {
	$this->background_cflag = $aName;
	$this->background_cflag_type = $aBgType;
	$this->background_cflag_mix = $aMix;
    }


    // Specify a background image
    function SetBackgroundImage($aFileName,$aBgType=BGIMG_FILLPLOT,$aImgFormat="auto") {

	if( $GLOBALS['gd2'] && !USE_TRUECOLOR ) {
	    JpGraphError::RaiseL(25017);//("You are using GD 2.x and are trying to use a background images on a non truecolor image. To use background images with GD 2.x you <b>must</b> enable truecolor by setting the USE_TRUECOLOR constant to TRUE. Due to a bug in GD 2.0.1 using any truetype fonts with truecolor images will result in very poor quality fonts.");
	}

	// Get extension to determine image type
	if( $aImgFormat == "auto" ) {
	    $e = explode('.',$aFileName);
	    if( !$e ) {
		JpGraphError::RaiseL(25018,$aFileName);//('Incorrect file name for Graph::SetBackgroundImage() : '.$aFileName.' Must have a valid image extension (jpg,gif,png) when using autodetection of image type');
	    }

	    $valid_formats = array('png', 'jpg', 'gif');
	    $aImgFormat = strtolower($e[count($e)-1]);
	    if ($aImgFormat == 'jpeg')  {
		$aImgFormat = 'jpg';
	    }
	    elseif (!in_array($aImgFormat, $valid_formats) )  {
		JpGraphError::RaiseL(25019,$aImgFormat);//('Unknown file extension ($aImgFormat) in Graph::SetBackgroundImage() for filename: '.$aFileName);
	    }    
	}

	$this->background_image = $aFileName;
	$this->background_image_type=$aBgType;
	$this->background_image_format=$aImgFormat;
    }

    function SetBackgroundImageMix($aMix) {
	$this->background_image_mix = $aMix ;
    }
	
    // Adjust brightness and constrast for background image
    function AdjBackgroundImage($aBright,$aContr=0,$aSat=0) {
	$this->background_image_bright=$aBright;
	$this->background_image_contr=$aContr;
	$this->background_image_sat=$aSat;
    }
	
    // Adjust brightness and constrast for image
    function AdjImage($aBright,$aContr=0,$aSat=0) {
	$this->image_bright=$aBright;
	$this->image_contr=$aContr;
	$this->image_sat=$aSat;
    }

    // Specify axis style (boxed or single)
    function SetAxisStyle($aStyle) {
        $this->iAxisStyle = $aStyle ;
    }
	
    // Set a frame around the plot area
    function SetBox($aDrawPlotFrame=true,$aPlotFrameColor=array(0,0,0),$aPlotFrameWeight=1) {
	$this->boxed = $aDrawPlotFrame;
	$this->box_weight = $aPlotFrameWeight;
	$this->box_color = $aPlotFrameColor;
    }
	
    // Specify color for the plotarea (not the margins)
    function SetColor($aColor) {
	$this->plotarea_color=$aColor;
    }
	
    // Specify color for the margins (all areas outside the plotarea)
    function SetMarginColor($aColor) {
	$this->margin_color=$aColor;
    }
	
    // Set a frame around the entire image
    function SetFrame($aDrawImgFrame=true,$aImgFrameColor=array(0,0,0),$aImgFrameWeight=1) {
	$this->doframe = $aDrawImgFrame;
	$this->frame_color = $aImgFrameColor;
	$this->frame_weight = $aImgFrameWeight;
    }

    function SetFrameBevel($aDepth=3,$aBorder=false,$aBorderColor='black',$aColor1='white@0.4',$aColor2='darkgray@0.4',$aFlg=true) {
	$this->framebevel = $aFlg ;
	$this->framebeveldepth = $aDepth ;
	$this->framebevelborder = $aBorder ;
	$this->framebevelbordercolor = $aBorderColor ;
	$this->framebevelcolor1 = $aColor1 ;
	$this->framebevelcolor2 = $aColor2 ;

	$this->doshadow = false ;
    }

    // Set the shadow around the whole image
    function SetShadow($aShowShadow=true,$aShadowWidth=5,$aShadowColor=array(102,102,102)) {
	$this->doshadow = $aShowShadow;
	$this->shadow_color = $aShadowColor;
	$this->shadow_width = $aShadowWidth;
	$this->footer->iBottomMargin += $aShadowWidth;
	$this->footer->iRightMargin += $aShadowWidth;
    }

    // Specify x,y scale. Note that if you manually specify the scale
    // you must also specify the tick distance with a call to Ticks::Set()
    function SetScale($aAxisType,$aYMin=1,$aYMax=1,$aXMin=1,$aXMax=1) {
	$this->axtype = $aAxisType;

	if( $aYMax < $aYMin || $aXMax < $aXMin )
	    JpGraphError::RaiseL(25020);//('Graph::SetScale(): Specified Max value must be larger than the specified Min value.');

	$yt=substr($aAxisType,-3,3);
	if( $yt=="lin" )
	    $this->yscale = new LinearScale($aYMin,$aYMax);
	elseif( $yt == "int" ) {
	    $this->yscale = new LinearScale($aYMin,$aYMax);
	    $this->yscale->SetIntScale();
	}
	elseif( $yt=="log" )
	    $this->yscale = new LogScale($aYMin,$aYMax);
	else
	    JpGraphError::RaiseL(25021,$aAxisType);//("Unknown scale specification for Y-scale. ($aAxisType)");
			
	$xt=substr($aAxisType,0,3);
	if( $xt == "lin" || $xt == "tex" ) {
	    $this->xscale = new LinearScale($aXMin,$aXMax,"x");
	    $this->xscale->textscale = ($xt == "tex");
	}
	elseif( $xt == "int" ) {
	    $this->xscale = new LinearScale($aXMin,$aXMax,"x");
	    $this->xscale->SetIntScale();
	}
	elseif( $xt == "dat" ) {
	    $this->xscale = new DateScale($aXMin,$aXMax,"x");
	}
	elseif( $xt == "log" )
	    $this->xscale = new LogScale($aXMin,$aXMax,"x");
	else
	    JpGraphError::RaiseL(25022,$aAxisType);//(" Unknown scale specification for X-scale. ($aAxisType)");

	$this->xaxis = new Axis($this->img,$this->xscale);
	$this->yaxis = new Axis($this->img,$this->yscale);
	$this->xgrid = new Grid($this->xaxis);
	$this->ygrid = new Grid($this->yaxis);	
	$this->ygrid->Show();			
    }
	
    // Specify secondary Y scale
    function SetY2Scale($aAxisType="lin",$aY2Min=1,$aY2Max=1) {
	if( $aAxisType=="lin" ) 
	    $this->y2scale = new LinearScale($aY2Min,$aY2Max);
	elseif( $aAxisType == "int" ) {
	    $this->y2scale = new LinearScale($aY2Min,$aY2Max);
	    $this->y2scale->SetIntScale();
	}
	elseif( $aAxisType=="log" ) {
	    $this->y2scale = new LogScale($aY2Min,$aY2Max);
	}
	else JpGraphError::RaiseL(25023,$aAxisType);//("JpGraph: Unsupported Y2 axis type: $aAxisType\nMust be one of (lin,log,int)");
			
	$this->y2axis = new Axis($this->img,$this->y2scale);
	$this->y2axis->scale->ticks->SetDirection(SIDE_LEFT); 
	$this->y2axis->SetLabelSide(SIDE_RIGHT); 
	$this->y2axis->SetPos('max');
	$this->y2axis->SetTitleSide(SIDE_RIGHT);
		
	// Deafult position is the max x-value
	$this->y2grid = new Grid($this->y2axis);							
    }

    // Set the delta position (in pixels) between the multiple Y-axis
    function SetYDeltaDist($aDist) {
	$this->iYAxisDeltaPos = $aDist;
    }
	
    // Specify secondary Y scale
    function SetYScale($aN,$aAxisType="lin",$aYMin=1,$aYMax=1) {

	if( $aAxisType=="lin" ) 
	    $this->ynscale[$aN] = new LinearScale($aYMin,$aYMax);
	elseif( $aAxisType == "int" ) {
	    $this->ynscale[$aN] = new LinearScale($aYMin,$aYMax);
	    $this->ynscale[$aN]->SetIntScale();
	}
	elseif( $aAxisType=="log" ) {
	    $this->ynscale[$aN] = new LogScale($aYMin,$aYMax);
	}
	else JpGraphError::RaiseL(25024,$aAxisType);//("JpGraph: Unsupported Y axis type: $aAxisType\nMust be one of (lin,log,int)");
			
	$this->ynaxis[$aN] = new Axis($this->img,$this->ynscale[$aN]);
	$this->ynaxis[$aN]->scale->ticks->SetDirection(SIDE_LEFT); 
	$this->ynaxis[$aN]->SetLabelSide(SIDE_RIGHT); 
    }

	
    // Specify density of ticks when autoscaling 'normal', 'dense', 'sparse', 'verysparse'
    // The dividing factor have been determined heuristically according to my aesthetic 
    // sense (or lack off) y.m.m.v !
    function SetTickDensity($aYDensity=TICKD_NORMAL,$aXDensity=TICKD_NORMAL) {
	$this->xtick_factor=30;
	$this->ytick_factor=25;		
	switch( $aYDensity ) {
	    case TICKD_DENSE:
		$this->ytick_factor=12;			
		break;
	    case TICKD_NORMAL:
		$this->ytick_factor=25;			
		break;
	    case TICKD_SPARSE:
		$this->ytick_factor=40;			
		break;
	    case TICKD_VERYSPARSE:
		$this->ytick_factor=100;			
		break;		
	    default:
		JpGraphError::RaiseL(25025,$densy);//("JpGraph: Unsupported Tick density: $densy");
	}
	switch( $aXDensity ) {
	    case TICKD_DENSE:
		$this->xtick_factor=15;							
		break;
	    case TICKD_NORMAL:
		$this->xtick_factor=30;			
		break;
	    case TICKD_SPARSE:
		$this->xtick_factor=45;					
		break;
	    case TICKD_VERYSPARSE:
		$this->xtick_factor=60;								
		break;		
	    default:
		JpGraphError::RaiseL(25025,$densx);//("JpGraph: Unsupported Tick density: $densx");
	}		
    }
	

    // Get a string of all image map areas	
    function GetCSIMareas() {
	if( !$this->iHasStroked )
	    $this->Stroke(_CSIM_SPECIALFILE);

	$csim = $this->title->GetCSIMAreas();
	$csim .= $this->subtitle->GetCSIMAreas();
	$csim .= $this->subsubtitle->GetCSIMAreas();
	$csim .= $this->legend->GetCSIMAreas();

	if( $this->y2axis != NULL ) {
	    $csim .= $this->y2axis->title->GetCSIMAreas();
	}

	if( $this->texts != null ) {
	    $n = count($this->texts);
	    for($i=0; $i < $n; ++$i ) {
		$csim .= $this->texts[$i]->GetCSIMAreas();
	    }
	}

	if( $this->y2texts != null && $this->y2scale != null ) {
	    $n = count($this->y2texts);
	    for($i=0; $i < $n; ++$i ) {
		$csim .= $this->y2texts[$i]->GetCSIMAreas();
	    }
	}

	if( $this->yaxis != null && $this->xaxis != null ) {
	    $csim .= $this->yaxis->title->GetCSIMAreas();	
	    $csim .= $this->xaxis->title->GetCSIMAreas();
	}

	$n = count($this->plots);
	for( $i=0; $i < $n; ++$i ) 
	    $csim .= $this->plots[$i]->GetCSIMareas();

	$n = count($this->y2plots);
	for( $i=0; $i < $n; ++$i ) 
	    $csim .= $this->y2plots[$i]->GetCSIMareas();

	$n = count($this->ynaxis);
	for( $i=0; $i < $n; ++$i ) {
	    $m = count($this->ynplots[$i]); 
	    for($j=0; $j < $m; ++$j ) {
		$csim .= $this->ynplots[$i][$j]->GetCSIMareas();
	    }
	}

	$n = count($this->iTables);
	for( $i=0; $i < $n; ++$i ) {
	    $csim .= $this->iTables[$i]->GetCSIMareas();
	}

	return $csim;
    }
	
    // Get a complete <MAP>..</MAP> tag for the final image map
    function GetHTMLImageMap($aMapName) {
	//$im = "<map name=\"$aMapName\" id=\"$aMapName\">\n";
	$im = "<map name=\"$aMapName\" />\n";
	$im .= $this->GetCSIMareas();
	$im .= "</map>"; 
	return $im;
    }

    function CheckCSIMCache($aCacheName,$aTimeOut=60) {
	global $_SERVER;

	if( $aCacheName=='auto' )
	    $aCacheName=basename($_SERVER['PHP_SELF']);

	$this->csimcachename = CSIMCACHE_DIR.$aCacheName;
	$this->csimcachetimeout = $aTimeOut;

	// First determine if we need to check for a cached version
	// This differs from the standard cache in the sense that the
	// image and CSIM map HTML file is written relative to the directory
	// the script executes in and not the specified cache directory.
	// The reason for this is that the cache directory is not necessarily
	// accessible from the HTTP server.
	if( $this->csimcachename != '' ) {
	    $dir = dirname($this->csimcachename);
	    $base = basename($this->csimcachename);
	    $base = strtok($base,'.');
	    $suffix = strtok('.');
	    $basecsim = $dir.'/'.$base.'_csim_.html';
	    $baseimg = $dir.'/'.$base.'.'.$this->img->img_format;

	    $timedout=false;
		
	    // Does it exist at all ?
	    
	    if( file_exists($basecsim) && file_exists($baseimg) ) {
		// Check that it hasn't timed out
		$diff=time()-filemtime($basecsim);
		if( $this->csimcachetimeout>0 && ($diff > $this->csimcachetimeout*60) ) {
		    $timedout=true;
		    @unlink($basecsim);
		    @unlink($baseimg);
		}
		else {
		    if ($fh = @fopen($basecsim, "r")) {
			fpassthru($fh);
			return true;
		    }
		    else
			JpGraphError::RaiseL(25027,$basecsim);//(" Can't open cached CSIM \"$basecsim\" for reading.");
		}
	    }
	}
	return false;
    }

    function StrokeCSIM($aScriptName='auto',$aCSIMName='',$aBorder=0) {
	if( $aCSIMName=='' ) {
	    // create a random map name
	    srand ((double) microtime() * 1000000);
	    $r = rand(0,100000);
	    $aCSIMName='__mapname'.$r.'__';
	}

	if( $aScriptName=='auto' )
	    $aScriptName=basename($_SERVER['PHP_SELF']);

	if( empty($_GET[_CSIM_DISPLAY]) ) {
	    // First determine if we need to check for a cached version
	    // This differs from the standard cache in the sense that the
	    // image and CSIM map HTML file is written relative to the directory
	    // the script executes in and not the specified cache directory.
	    // The reason for this is that the cache directory is not necessarily
	    // accessible from the HTTP server.
	    if( $this->csimcachename != '' ) {
		$dir = dirname($this->csimcachename);
		$base = basename($this->csimcachename);
		$base = strtok($base,'.');
		$suffix = strtok('.');
		$basecsim = $dir.'/'.$base.'_csim_.html';
		$baseimg = $base.'.'.$this->img->img_format;

		// Check that apache can write to directory specified

		if( file_exists($dir) && !is_writeable($dir) ) {
		    JpgraphError::RaiseL(25028,$dir);//('Apache/PHP does not have permission to write to the CSIM cache directory ('.$dir.'). Check permissions.');
		}
		
		// Make sure directory exists
		$this->cache->MakeDirs($dir);

		// Write the image file
		$this->Stroke(CSIMCACHE_DIR.$baseimg);

		// Construct wrapper HTML and write to file and send it back to browser
		$htmlwrap = $this->GetHTMLImageMap($aCSIMName)."\n".
		    '<img src="'.htmlentities(CSIMCACHE_HTTP_DIR.$baseimg).'" ismap usemap="#'.$aCSIMName.'" border='.$aBorder.' width='.$this->img->width.' height='.$this->img->height." alt=\"\" />\n";
		if($fh =  @fopen($basecsim,'w') ) {
		    fwrite($fh,$htmlwrap);
		    fclose($fh);
		    echo $htmlwrap;
		}
		else
		    JpGraphError::RaiseL(25029,$basecsim);//(" Can't write CSIM \"$basecsim\" for writing. Check free space and permissions.");
	    }
	    else {

		if( $aScriptName=='' ) {
		    JpGraphError::RaiseL(25030);//('Missing script name in call to StrokeCSIM(). You must specify the name of the actual image script as the first parameter to StrokeCSIM().');
		    exit();
		}

		
		// This is a JPGRAPH internal defined that prevents
		// us from recursively coming here again
		$urlarg='?'._CSIM_DISPLAY.'=1';

		// Now reconstruct any user URL argument
		reset($_GET);
		while( list($key,$value) = each($_GET) ) {
		    if( is_array($value) ) {
			$n = count($value);
			for( $i=0; $i < $n; ++$i ) {
			    $urlarg .= '&'.$key.'%5B%5D='.urlencode($value[$i]);
			}
		    }
		    else {
			$urlarg .= '&'.$key.'='.urlencode($value);
		    }
		}

		// It's not ideal to convert POST argument to GET arguments
		// but there is little else we can do. One idea for the 
		// future might be recreate the POST header in case.
		reset($_POST);
		while( list($key,$value) = each($_POST) ) {
		    if( is_array($value) ) {
			$n = count($value);
			for( $i=0; $i < $n; ++$i ) {
			    $urlarg .= '&'.$key.'%5B%5D='.urlencode($value[$i]);
			}
		    }
		    else {
			$urlarg .= '&'.$key.'='.urlencode($value);
		    }
		}

		echo $this->GetHTMLImageMap($aCSIMName);

		echo "<img src='".htmlentities($aScriptName.$urlarg)."' ismap usemap='#".$aCSIMName.'\' border='.$aBorder.'  width='.$this->img->width.' height='.$this->img->height." alt=\"\" />\n";
	    }
	}
	else {
	    $this->Stroke();
	}
    }

    function GetTextsYMinMax($aY2=false) {
	if( $aY2 ) 
	    $txts = $this->y2texts;
	else
	    $txts = $this->texts;
	$n = count($txts);
	$min=null;
	$max=null;
	for( $i=0; $i < $n; ++$i ) {
	    if( $txts[$i]->iScalePosY !== null && 
		$txts[$i]->iScalePosX !== null  ) {
		if( $min === null  ) {
		    $min = $max = $txts[$i]->iScalePosY ;
		}
		else {
		    $min = min($min,$txts[$i]->iScalePosY);
		    $max = max($max,$txts[$i]->iScalePosY);
		}
	    }
	}
	if( $min !== null ) {
	    return array($min,$max);
	}
	else
	    return null;
    }

    function GetTextsXMinMax($aY2=false) {
	if( $aY2 ) 
	    $txts = $this->y2texts;
	else
	    $txts = $this->texts;
	$n = count($txts);
	$min=null;
	$max=null;
	for( $i=0; $i < $n; ++$i ) {
	    if( $txts[$i]->iScalePosY !== null && 
		$txts[$i]->iScalePosX !== null  ) {
		if( $min === null  ) {
		    $min = $max = $txts[$i]->iScalePosX ;
		}
		else {
		    $min = min($min,$txts[$i]->iScalePosX);
		    $max = max($max,$txts[$i]->iScalePosX);
		}
	    }
	}
	if( $min !== null ) {
	    return array($min,$max);
	}
	else
	    return null;
    }

    function GetXMinMax() {
	list($min,$ymin) = $this->plots[0]->Min();
	list($max,$ymax) = $this->plots[0]->Max();
	foreach( $this->plots as $p ) {
	    list($xmin,$ymin) = $p->Min();
	    list($xmax,$ymax) = $p->Max();			
	    $min = Min($xmin,$min);
	    $max = Max($xmax,$max);
	}
	if( $this->y2axis != null ) {
	    foreach( $this->y2plots as $p ) {
		list($xmin,$ymin) = $p->Min();
		list($xmax,$ymax) = $p->Max();			
		$min = Min($xmin,$min);
		$max = Max($xmax,$max);
	    }		    
	}

	$n = count($this->ynaxis);
	for( $i=0; $i < $n; ++$i ) {
	    if( $this->ynaxis[$i] != null) {
		foreach( $this->ynplots[$i] as $p ) {
		    list($xmin,$ymin) = $p->Min();
		    list($xmax,$ymax) = $p->Max();			
		    $min = Min($xmin,$min);
		    $max = Max($xmax,$max);
		}		    
	    }
	}

	return array($min,$max);
    }

    function AdjustMarginsForTitles() {
	$totrequired = 
	    ($this->title->t != '' ? 
	     $this->title->GetTextHeight($this->img) + $this->title->margin + 5 : 0 ) +
	    ($this->subtitle->t != '' ? 
	     $this->subtitle->GetTextHeight($this->img) + $this->subtitle->margin + 5 : 0 ) + 
	    ($this->subsubtitle->t != '' ? 
	     $this->subsubtitle->GetTextHeight($this->img) + $this->subsubtitle->margin + 5 : 0 ) ;
	

	$btotrequired = 0;
	if($this->xaxis != null &&  !$this->xaxis->hide && !$this->xaxis->hide_labels ) {
	    // Minimum bottom margin
	    if( $this->xaxis->title->t != '' ) {
		if( $this->img->a == 90 ) 
		    $btotrequired = $this->yaxis->title->GetTextHeight($this->img) + 5 ;
		else
		    $btotrequired = $this->xaxis->title->GetTextHeight($this->img) + 5 ;
	    }
	    else
		$btotrequired = 0;
	    
	    if( $this->img->a == 90 ) {
		$this->img->SetFont($this->yaxis->font_family,$this->yaxis->font_style,
				    $this->yaxis->font_size);
		$lh = $this->img->GetTextHeight('Mg',$this->yaxis->label_angle);
	    }
	    else {
		$this->img->SetFont($this->xaxis->font_family,$this->xaxis->font_style,
				    $this->xaxis->font_size);
		$lh = $this->img->GetTextHeight('Mg',$this->xaxis->label_angle);
	    }
	    
	    $btotrequired += $lh + 5;
	}

	if( $this->img->a == 90 ) {
	    // DO Nothing. It gets too messy to do this properly for 90 deg...
	}
	else{
	    if( $this->img->top_margin < $totrequired ) {
		$this->SetMargin($this->img->left_margin,$this->img->right_margin,
				 $totrequired,$this->img->bottom_margin);
	    }
	    if( $this->img->bottom_margin < $btotrequired ) {
		$this->SetMargin($this->img->left_margin,$this->img->right_margin,
				 $this->img->top_margin,$btotrequired);
	    }
	}
    }

    // Stroke the graph
    // $aStrokeFileName	If != "" the image will be written to this file and NOT
    // streamed back to the browser
    function Stroke($aStrokeFileName="") {		

	// Fist make a sanity check that user has specified a scale
	if( empty($this->yscale) ) {
	    JpGraphError::RaiseL(25031);//('You must specify what scale to use with a call to Graph::SetScale().');
	}

	// Start by adjusting the margin so that potential titles will fit.
	$this->AdjustMarginsForTitles();

	// Setup scale constants
	if( $this->yscale ) $this->yscale->InitConstants($this->img);
	if( $this->xscale ) $this->xscale->InitConstants($this->img);
	if( $this->y2scale ) $this->y2scale->InitConstants($this->img);
	
	$n=count($this->ynscale);
	for($i=0; $i < $n; ++$i) {
	  if( $this->ynscale[$i] ) $this->ynscale[$i]->InitConstants($this->img);
	}

	// If the filename is the predefined value = '_csim_special_'
	// we assume that the call to stroke only needs to do enough
	// to correctly generate the CSIM maps.
	// We use this variable to skip things we don't strictly need
	// to do to generate the image map to improve performance
	// a best we can. Therefor you will see a lot of tests !$_csim in the
	// code below.
	$_csim = ($aStrokeFileName===_CSIM_SPECIALFILE);

	// We need to know if we have stroked the plot in the
	// GetCSIMareas. Otherwise the CSIM hasn't been generated
	// and in the case of GetCSIM called before stroke to generate
	// CSIM without storing an image to disk GetCSIM must call Stroke.
	$this->iHasStroked = true;

	// Do any pre-stroke adjustment that is needed by the different plot types
	// (i.e bar plots want's to add an offset to the x-labels etc)
	for($i=0; $i < count($this->plots) ; ++$i ) {
	    $this->plots[$i]->PreStrokeAdjust($this);
	    $this->plots[$i]->DoLegend($this);
	}
		
	// Any plots on the second Y scale?
	if( $this->y2scale != null ) {
	    for($i=0; $i<count($this->y2plots)	; ++$i ) {
		$this->y2plots[$i]->PreStrokeAdjust($this);
		$this->y2plots[$i]->DoLegend($this);
	    }
	}

	// Any plots on the extra Y axises?
	$n = count($this->ynaxis);
	for($i=0; $i<$n	; ++$i ) {
	    if( $this->ynplots == null || $this->ynplots[$i] == null) {
		JpGraphError::RaiseL(25032,$i);//("No plots for Y-axis nbr:$i");
	    } 
	    $m = count($this->ynplots[$i]); 
	    for($j=0; $j < $m; ++$j ) {
		$this->ynplots[$i][$j]->PreStrokeAdjust($this);
		$this->ynplots[$i][$j]->DoLegend($this);
	    }
	}

		
	// Bail out if any of the Y-axis not been specified and
	// has no plots. (This means it is impossible to do autoscaling and
	// no other scale was given so we can't possible draw anything). If you use manual
	// scaling you also have to supply the tick steps as well.
	if( (!$this->yscale->IsSpecified() && count($this->plots)==0) ||
	    ($this->y2scale!=null && !$this->y2scale->IsSpecified() && count($this->y2plots)==0) ) {
	    //$e = "n=".count($this->y2plots)."\n";
	    // $e = "Can't draw unspecified Y-scale.<br>\nYou have either:<br>\n";
	    // $e .= "1. Specified an Y axis for autoscaling but have not supplied any plots<br>\n";
	    // $e .= "2. Specified a scale manually but have forgot to specify the tick steps";
	    JpGraphError::RaiseL(25026);
	}
		
	// Bail out if no plots and no specified X-scale
	if( (!$this->xscale->IsSpecified() && count($this->plots)==0 && count($this->y2plots)==0) )
	    JpGraphError::RaiseL(25034);//("<strong>JpGraph: Can't draw unspecified X-scale.</strong><br>No plots.<br>");

	//Check if we should autoscale y-axis
	if( !$this->yscale->IsSpecified() && count($this->plots)>0 ) {
	    list($min,$max) = $this->GetPlotsYMinMax($this->plots);
 	    $lres = $this->GetLinesYMinMax($this->lines);
	    if( is_array($lres) ) {
		list($linmin,$linmax) = $lres ;
		$min = min($min,$linmin);
		$max = max($max,$linmax);
	    }
	    $tres = $this->GetTextsYMinMax();
	    if( is_array($tres) ) {
		list($tmin,$tmax) = $tres ;
		$min = min($min,$tmin);
		$max = max($max,$tmax);
	    }
	    $this->yscale->AutoScale($this->img,$min,$max,
				     $this->img->plotheight/$this->ytick_factor);
	}
	elseif( $this->yscale->IsSpecified() && 
		( $this->yscale->auto_ticks || !$this->yscale->ticks->IsSpecified()) ) {
	    // The tick calculation will use the user suplied min/max values to determine
	    // the ticks. If auto_ticks is false the exact user specifed min and max
	    // values will be used for the scale. 
	    // If auto_ticks is true then the scale might be slightly adjusted
	    // so that the min and max values falls on an even major step.
	    $min = $this->yscale->scale[0];
	    $max = $this->yscale->scale[1];
	    $this->yscale->AutoScale($this->img,$min,$max,
				     $this->img->plotheight/$this->ytick_factor,
				     $this->yscale->auto_ticks);
	}

	if( $this->y2scale != null) {
	  
	    if( !$this->y2scale->IsSpecified() && count($this->y2plots)>0 ) {
		list($min,$max) = $this->GetPlotsYMinMax($this->y2plots);
		$lres = $this->GetLinesYMinMax($this->y2lines);
		if( is_array($lres) ) {
		    list($linmin,$linmax) = $lres ;
		    $min = min($min,$linmin);
		    $max = max($max,$linmax);
		}
		$tres = $this->GetTextsYMinMax(true);
		if( is_array($tres) ) {
		    list($tmin,$tmax) = $tres ;
		    $min = min($min,$tmin);
		    $max = max($max,$tmax);
		}
		$this->y2scale->AutoScale($this->img,$min,$max,$this->img->plotheight/$this->ytick_factor);
	    }			
	    elseif( $this->y2scale->IsSpecified() && 
		    ( $this->y2scale->auto_ticks || !$this->y2scale->ticks->IsSpecified()) ) {
		// The tick calculation will use the user suplied min/max values to determine
		// the ticks. If auto_ticks is false the exact user specifed min and max
		// values will be used for the scale. 
		// If auto_ticks is true then the scale might be slightly adjusted
		// so that the min and max values falls on an even major step.
		$min = $this->y2scale->scale[0];
		$max = $this->y2scale->scale[1];
		$this->y2scale->AutoScale($this->img,$min,$max,
					  $this->img->plotheight/$this->ytick_factor,
					  $this->y2scale->auto_ticks);
	    }
	}

	//
	// Autoscale the multiple Y-axis
	//
	$n = count($this->ynaxis);
	for( $i=0; $i < $n; ++$i ) {
	  if( $this->ynscale[$i] != null) {
	    if( !$this->ynscale[$i]->IsSpecified() && count($this->ynplots[$i])>0 ) {
	      list($min,$max) = $this->GetPlotsYMinMax($this->ynplots[$i]);
	      $this->ynscale[$i]->AutoScale($this->img,$min,$max,$this->img->plotheight/$this->ytick_factor);
	    }			
	    elseif( $this->ynscale[$i]->IsSpecified() && 
		    ( $this->ynscale[$i]->auto_ticks || !$this->ynscale[$i]->ticks->IsSpecified()) ) {
		// The tick calculation will use the user suplied min/max values to determine
		// the ticks. If auto_ticks is false the exact user specifed min and max
		// values will be used for the scale. 
		// If auto_ticks is true then the scale might be slightly adjusted
		// so that the min and max values falls on an even major step.
	      $min = $this->ynscale[$i]->scale[0];
	      $max = $this->ynscale[$i]->scale[1];
	      $this->ynscale[$i]->AutoScale($this->img,$min,$max,
					    $this->img->plotheight/$this->ytick_factor,
					    $this->ynscale[$i]->auto_ticks);
	    }
	  }
	}
		

	//Check if we should autoscale x-axis
	if( !$this->xscale->IsSpecified() ) {
	    if( substr($this->axtype,0,4) == "text" ) {
		$max=0;
		$n = count($this->plots);
		for($i=0; $i < $n; ++$i ) {
		    $p = $this->plots[$i];
		    // We need some unfortunate sub class knowledge here in order
		    // to increase number of data points in case it is a line plot
		    // which has the barcenter set. If not it could mean that the
		    // last point of the data is outside the scale since the barcenter
		    // settings means that we will shift the entire plot half a tick step
		    // to the right in oder to align with the center of the bars.
		    if( is_a($p,'BarPlot') || empty($p->barcenter)) {
			$max=max($max,$p->numpoints-1);
		    }
		    else {
			$max=max($max,$p->numpoints);
		    }
		}
		$min=0;
		if( $this->y2axis != null ) {
		    foreach( $this->y2plots as $p ) {
			$max=max($max,$p->numpoints-1);
		    }		    
		}
		$n = count($this->ynaxis);
		for( $i=0; $i < $n; ++$i ) {
		    if( $this->ynaxis[$i] != null) {
			foreach( $this->ynplots[$i] as $p ) {
			    $max=max($max,$p->numpoints-1);
			}		    
		    }
		}
		
		$this->xscale->Update($this->img,$min,$max);
		$this->xscale->ticks->Set($this->xaxis->tick_step,1);
		$this->xscale->ticks->SupressMinorTickMarks();
	    }
	    else {
		list($min,$max) = $this->GetXMinMax();
		$lres = $this->GetLinesXMinMax($this->lines);
		if( $lres ) {
		    list($linmin,$linmax) = $lres ;
		    $min = min($min,$linmin);
		    $max = max($max,$linmax);
		}
		$lres = $this->GetLinesXMinMax($this->y2lines);
		if( $lres ) {
		    list($linmin,$linmax) = $lres ;
		    $min = min($min,$linmin);
		    $max = max($max,$linmax);
		}

		$tres = $this->GetTextsXMinMax();
		if( $tres ) {
		    list($tmin,$tmax) = $tres ;
		    $min = min($min,$tmin);
		    $max = max($max,$tmax);
		}

		$tres = $this->GetTextsXMinMax(true);
		if( $tres ) {
		    list($tmin,$tmax) = $tres ;
		    $min = min($min,$tmin);
		    $max = max($max,$tmax);
		}

		$this->xscale->AutoScale($this->img,$min,$max,round($this->img->plotwidth/$this->xtick_factor));
	    }
			
	    //Adjust position of y-axis and y2-axis to minimum/maximum of x-scale
	    if( !is_numeric($this->yaxis->pos) && !is_string($this->yaxis->pos) )
	    	$this->yaxis->SetPos($this->xscale->GetMinVal());
	    if( $this->y2axis != null ) {
		if( !is_numeric($this->y2axis->pos) && !is_string($this->y2axis->pos) )
		    $this->y2axis->SetPos($this->xscale->GetMaxVal());
		$this->y2axis->SetTitleSide(SIDE_RIGHT);
	    }

	    $n = count($this->ynaxis);
	    $nY2adj = $this->y2axis != null ? $this->iYAxisDeltaPos : 0;
	    for( $i=0; $i < $n; ++$i ) { 
		if( $this->ynaxis[$i] != null ) {
		    if( !is_numeric($this->ynaxis[$i]->pos) && !is_string($this->ynaxis[$i]->pos) ) {
			$this->ynaxis[$i]->SetPos($this->xscale->GetMaxVal());
		  $this->ynaxis[$i]->SetPosAbsDelta($i*$this->iYAxisDeltaPos + $nY2adj);
		    }
		    $this->ynaxis[$i]->SetTitleSide(SIDE_RIGHT);
		}
	    }
	}	
	elseif( $this->xscale->IsSpecified() &&  
		( $this->xscale->auto_ticks || !$this->xscale->ticks->IsSpecified()) ) {
	    // The tick calculation will use the user suplied min/max values to determine
	    // the ticks. If auto_ticks is false the exact user specifed min and max
	    // values will be used for the scale. 
	    // If auto_ticks is true then the scale might be slightly adjusted
	    // so that the min and max values falls on an even major step.
	    $min = $this->xscale->scale[0];
	    $max = $this->xscale->scale[1];


	    $this->xscale->AutoScale($this->img,$min,$max,
				     $this->img->plotwidth/$this->xtick_factor,
				     false);

	    if( $this->y2axis != null ) {
		if( !is_numeric($this->y2axis->pos) && !is_string($this->y2axis->pos) )
		    $this->y2axis->SetPos($this->xscale->GetMaxVal());
		$this->y2axis->SetTitleSide(SIDE_RIGHT);
	    }

	}
		
	// If we have a negative values and x-axis position is at 0
	// we need to supress the first and possible the last tick since
	// they will be drawn on top of the y-axis (and possible y2 axis)
	// The test below might seem strange the reasone being that if
	// the user hasn't specified a value for position this will not
	// be set until we do the stroke for the axis so as of now it
	// is undefined.
	// For X-text scale we ignore all this since the tick are usually
	// much further in and not close to the Y-axis. Hence the test 
	// for 'text'	

	if( ($this->yaxis->pos==$this->xscale->GetMinVal() || 
	     (is_string($this->yaxis->pos) && $this->yaxis->pos=='min')) &&  
	    !is_numeric($this->xaxis->pos) && $this->yscale->GetMinVal() < 0 && 
	    substr($this->axtype,0,4) != 'text' && $this->xaxis->pos!="min" ) {

	    //$this->yscale->ticks->SupressZeroLabel(false);
	    $this->xscale->ticks->SupressFirst();
	    if( $this->y2axis != null ) {
		$this->xscale->ticks->SupressLast();
	    }
	}
	elseif( !is_numeric($this->yaxis->pos) && $this->yaxis->pos=='max' ) {
	    $this->xscale->ticks->SupressLast();
	}
	

	if( !$_csim ) {
	    $this->StrokePlotArea();
	    if( $this->iIconDepth == DEPTH_BACK ) {
		$this->StrokeIcons();
	    }
	}
	$this->StrokeAxis();

	// Stroke bands
	if( $this->bands != null && !$_csim) 
	    for($i=0; $i < count($this->bands); ++$i) {
		// Stroke all bands that asks to be in the background
		if( $this->bands[$i]->depth == DEPTH_BACK )
		    $this->bands[$i]->Stroke($this->img,$this->xscale,$this->yscale);
	    }

	if( $this->y2bands != null && $this->y2scale != null && !$_csim )
	    for($i=0; $i < count($this->y2bands); ++$i) {
		// Stroke all bands that asks to be in the foreground
		if( $this->y2bands[$i]->depth == DEPTH_BACK )
		    $this->y2bands[$i]->Stroke($this->img,$this->xscale,$this->y2scale);
	    }


	if( $this->grid_depth == DEPTH_BACK && !$_csim) {
	    $this->ygrid->Stroke();
	    $this->xgrid->Stroke();
	}
				
	// Stroke Y2-axis 
	if( $this->y2axis != null && !$_csim) {		
	    $this->y2axis->Stroke($this->xscale); 				
	    $this->y2grid->Stroke();
	}

	// Stroke yn-axis
	$n = count($this->ynaxis); 
	for( $i=0; $i < $n; ++$i ) {
	    $this->ynaxis[$i]->Stroke($this->xscale); 				
	}
	
	$oldoff=$this->xscale->off;
	if(substr($this->axtype,0,4)=="text") {
	    if( $this->text_scale_abscenteroff > -1 ) {
		// For a text scale the scale factor is the number of pixel per step. 
		// Hence we can use the scale factor as a substitute for number of pixels
		// per major scale step and use that in order to adjust the offset so that
		// an object of width "abscenteroff" becomes centered.
		$this->xscale->off += round($this->xscale->scale_factor/2)-round($this->text_scale_abscenteroff/2);
	    }
	    else {
		$this->xscale->off += 
		    ceil($this->xscale->scale_factor*$this->text_scale_off*$this->xscale->ticks->minor_step);
	    }
	}

	if( $this->iDoClipping ) {
	    $oldimage = $this->img->CloneCanvasH();
	}

	if( ! $this->y2orderback ) {
	    // Stroke all plots for Y axis
	    for($i=0; $i < count($this->plots); ++$i) {
		$this->plots[$i]->Stroke($this->img,$this->xscale,$this->yscale);
		$this->plots[$i]->StrokeMargin($this->img);
	    }						
	}

	// Stroke all plots for Y2 axis
	if( $this->y2scale != null )
	    for($i=0; $i< count($this->y2plots); ++$i ) {	
		$this->y2plots[$i]->Stroke($this->img,$this->xscale,$this->y2scale);
	    }		

	if( $this->y2orderback ) {
	    // Stroke all plots for Y1 axis
	    for($i=0; $i < count($this->plots); ++$i) {
		$this->plots[$i]->Stroke($this->img,$this->xscale,$this->yscale);
		$this->plots[$i]->StrokeMargin($this->img);
	    }						
	}

	$n = count($this->ynaxis); 
	for( $i=0; $i < $n; ++$i ) {
	    $m = count($this->ynplots[$i]);
	    for( $j=0; $j < $m; ++$j ) { 
		$this->ynplots[$i][$j]->Stroke($this->img,$this->xscale,$this->ynscale[$i]);
		$this->ynplots[$i][$j]->StrokeMargin($this->img);
	    }
	}

	if( $this->iIconDepth == DEPTH_FRONT) {
	    $this->StrokeIcons();
	}
	
	if( $this->iDoClipping ) {
	    // Clipping only supports graphs at 0 and 90 degrees
	    if( $this->img->a == 0 ) {
		$this->img->CopyCanvasH($oldimage,$this->img->img,
					$this->img->left_margin,$this->img->top_margin,
					$this->img->left_margin,$this->img->top_margin,
					$this->img->plotwidth+1,$this->img->plotheight);
	    }
	    elseif( $this->img->a == 90 ) {
		$adj = ($this->img->height - $this->img->width)/2;
		$this->img->CopyCanvasH($oldimage,$this->img->img,
					$this->img->bottom_margin-$adj,$this->img->left_margin+$adj,
					$this->img->bottom_margin-$adj,$this->img->left_margin+$adj,
					$this->img->plotheight+1,$this->img->plotwidth);
	    }
	    else {
		JpGraphError::RaiseL(25035,$this->img->a);//('You have enabled clipping. Cliping is only supported for graphs at 0 or 90 degrees rotation. Please adjust you current angle (='.$this->img->a.' degrees) or disable clipping.');
	    }
	    $this->img->Destroy();
	    $this->img->SetCanvasH($oldimage);
	}

	$this->xscale->off=$oldoff;
		
	if( $this->grid_depth == DEPTH_FRONT && !$_csim ) {
	    $this->ygrid->Stroke();
	    $this->xgrid->Stroke();
	}

	// Stroke bands
	if( $this->bands!= null )
	    for($i=0; $i < count($this->bands); ++$i) {
		// Stroke all bands that asks to be in the foreground
		if( $this->bands[$i]->depth == DEPTH_FRONT )
		    $this->bands[$i]->Stroke($this->img,$this->xscale,$this->yscale);
	    }

	if( $this->y2bands!= null && $this->y2scale != null )
	    for($i=0; $i < count($this->y2bands); ++$i) {
		// Stroke all bands that asks to be in the foreground
		if( $this->y2bands[$i]->depth == DEPTH_FRONT )
		    $this->y2bands[$i]->Stroke($this->img,$this->xscale,$this->y2scale);
	    }


	// Stroke any lines added
	if( $this->lines != null ) {
	    for($i=0; $i < count($this->lines); ++$i) {
		$this->lines[$i]->Stroke($this->img,$this->xscale,$this->yscale);
	    }
	}

	if( $this->y2lines != null && $this->y2scale != null ) {
	    for($i=0; $i < count($this->y2lines); ++$i) {
		$this->y2lines[$i]->Stroke($this->img,$this->xscale,$this->y2scale);
	    }
	}

	// Finally draw the axis again since some plots may have nagged
	// the axis in the edges.However we do no stroke the labels again
	// since any user defined callback would be called twice. It also
	// enhances performance.

	if( !$_csim )
	    $this->StrokeAxis(false);

	if( $this->y2scale != null && !$_csim ) 
	    $this->y2axis->Stroke($this->xscale,false); 	
		
	if( !$_csim ) {
	    $this->StrokePlotBox();
	}
		
	// The titles and legends never gets rotated so make sure
	// that the angle is 0 before stroking them				
	$aa = $this->img->SetAngle(0);
	$this->StrokeTitles();
	$this->footer->Stroke($this->img);
	$this->legend->Stroke($this->img);		
	$this->img->SetAngle($aa);	
	$this->StrokeTexts();	
	$this->StrokeTables();

	if( !$_csim ) {

	    $this->img->SetAngle($aa);	
			
	    // Draw an outline around the image map	
	    if(_JPG_DEBUG) {
		$this->DisplayClientSideaImageMapAreas();		
	    }
	    
	    // Adjust the appearance of the image
	    $this->AdjustSaturationBrightnessContrast();

	    // Should we do any final image transformation
	    if( $this->iImgTrans ) {
		if( !class_exists('ImgTrans') ) {
		    require_once('jpgraph_imgtrans.php');
		    //JpGraphError::Raise('In order to use image transformation you must include the file jpgraph_imgtrans.php in your script.');
		}
	       
		$tform = new ImgTrans($this->img->img);
		$this->img->img = $tform->Skew3D($this->iImgTransHorizon,$this->iImgTransSkewDist,
						 $this->iImgTransDirection,$this->iImgTransHighQ,
						 $this->iImgTransMinSize,$this->iImgTransFillColor,
						 $this->iImgTransBorder);
	    }

	    // If the filename is given as the special "__handle"
	    // then the image handler is returned and the image is NOT
	    // streamed back
	    if( $aStrokeFileName == _IMG_HANDLER ) {
		return $this->img->img;
	    }
	    else {
		// Finally stream the generated picture					
		$this->cache->PutAndStream($this->img,$this->cache_name,$this->inline,$aStrokeFileName);		
	    }
	}
    }

    function SetAxisLabelBackground($aType,$aXFColor='lightgray',$aXColor='black',$aYFColor='lightgray',$aYColor='black') {
	$this->iAxisLblBgType = $aType;
	$this->iXAxisLblBgFillColor = $aXFColor;
	$this->iXAxisLblBgColor = $aXColor;
	$this->iYAxisLblBgFillColor = $aYFColor;
	$this->iYAxisLblBgColor = $aYColor;
    }

//---------------
// PRIVATE METHODS	

    function StrokeAxisLabelBackground() {
	// Types 
	// 0 = No background
	// 1 = Only X-labels, length of axis
	// 2 = Only Y-labels, length of axis
	// 3 = As 1 but extends to width of graph
	// 4 = As 2 but extends to height of graph
	// 5 = Combination of 3 & 4
	// 6 = Combination of 1 & 2
 
	$t = $this->iAxisLblBgType ;
	if( $t < 1 ) return;
	// Stroke optional X-axis label background color
	if( $t == 1 || $t == 3 || $t == 5 || $t == 6 ) {
	    $this->img->PushColor($this->iXAxisLblBgFillColor);
	    if( $t == 1 || $t == 6 ) {
		$xl = $this->img->left_margin;
		$yu = $this->img->height - $this->img->bottom_margin + 1;
		$xr = $this->img->width - $this->img->right_margin ;
		$yl = $this->img->height-1-$this->frame_weight;
	    }
	    else { // t==3 || t==5
		$xl = $this->frame_weight;
		$yu = $this->img->height - $this->img->bottom_margin + 1;
		$xr = $this->img->width - 1 - $this->frame_weight;
		$yl = $this->img->height-1-$this->frame_weight;
	    }

	    $this->img->FilledRectangle($xl,$yu,$xr,$yl);
	    $this->img->PopColor();

	    // Check if we should add the vertical lines at left and right edge
	    if( $this->iXAxisLblBgColor !== '' ) {
		$this->img->PushColor($this->iXAxisLblBgColor);
		if( $t == 1 || $t == 6 ) {
		    $this->img->Line($xl,$yu,$xl,$yl);
		    $this->img->Line($xr,$yu,$xr,$yl);
		}
		else {
		    $xl = $this->img->width - $this->img->right_margin ;
		    $this->img->Line($xl,$yu-1,$xr,$yu-1);
		}
		$this->img->PopColor();
	    }
	}

	if( $t == 2 || $t == 4 || $t == 5 || $t == 6 ) {
	    $this->img->PushColor($this->iYAxisLblBgFillColor);
	    if( $t == 2 || $t == 6 ) {	    
		$xl = $this->frame_weight;
		$yu = $this->frame_weight+$this->img->top_margin;
		$xr = $this->img->left_margin - 1;
		$yl = $this->img->height - $this->img->bottom_margin + 1;
	    }
	    else {
		$xl = $this->frame_weight;
		$yu = $this->frame_weight;
		$xr = $this->img->left_margin - 1;
		$yl = $this->img->height-1-$this->frame_weight;
	    }

	    $this->img->FilledRectangle($xl,$yu,$xr,$yl);
	    $this->img->PopColor();

	    // Check if we should add the vertical lines at left and right edge
	    if( $this->iXAxisLblBgColor !== '' ) {
		$this->img->PushColor($this->iXAxisLblBgColor);
		if( $t == 2 || $t == 6 ) {
		    $this->img->Line($xl,$yu-1,$xr,$yu-1);
		    $this->img->Line($xl,$yl-1,$xr,$yl-1);		    
		}
		else {
		    $this->img->Line($xr+1,$yu,$xr+1,$this->img->top_margin);		    
		}
		$this->img->PopColor();
	    }

	}
    }

    function StrokeAxis($aStrokeLabels=true) {
	
	if( $aStrokeLabels ) {
	    $this->StrokeAxisLabelBackground();
	}

	// Stroke axis
	if( $this->iAxisStyle != AXSTYLE_SIMPLE ) {
	    switch( $this->iAxisStyle ) {
	        case AXSTYLE_BOXIN :
	            $toppos = SIDE_DOWN;
		    $bottompos = SIDE_UP;
	            $leftpos = SIDE_RIGHT;
	            $rightpos = SIDE_LEFT;
	            break;
		case AXSTYLE_BOXOUT :
		    $toppos = SIDE_UP;
	            $bottompos = SIDE_DOWN;	    
	            $leftpos = SIDE_LEFT;
		    $rightpos = SIDE_RIGHT;
	            break;
		case AXSTYLE_YBOXIN:
	            $toppos = -100;
		    $bottompos = SIDE_UP;
	            $leftpos = SIDE_RIGHT;
	            $rightpos = SIDE_LEFT;
		    break;
		case AXSTYLE_YBOXOUT:
		    $toppos = -100;
	            $bottompos = SIDE_DOWN;	    
	            $leftpos = SIDE_LEFT;
		    $rightpos = SIDE_RIGHT;
		    break;
		default:
	            JpGRaphError::RaiseL(25036,$this->iAxisStyle); //('Unknown AxisStyle() : '.$this->iAxisStyle);
	            break;
	    }
	    $this->xaxis->SetPos('min');
	    
	    // By default we hide the first label so it doesn't cross the
	    // Y-axis in case the positon hasn't been set by the user.
	    // However, if we use a box we always want the first value
	    // displayed so we make sure it will be displayed.
	    $this->xscale->ticks->SupressFirst(false);
	    
	    $this->xaxis->SetLabelSide(SIDE_DOWN);
	    $this->xaxis->scale->ticks->SetSide($bottompos);
	    $this->xaxis->Stroke($this->yscale);

	    if( $toppos != -100 ) {
		// To avoid side effects we work on a new copy
		$maxis = $this->xaxis;
		$maxis->SetPos('max');
		$maxis->SetLabelSide(SIDE_UP);
		$maxis->SetLabelMargin(7);
		$this->xaxis->scale->ticks->SetSide($toppos);
		$maxis->Stroke($this->yscale);
	    }

	    $this->yaxis->SetPos('min');
	    $this->yaxis->SetLabelMargin(10);
	    $this->yaxis->SetLabelSide(SIDE_LEFT);
	    $this->yaxis->scale->ticks->SetSide($leftpos);
	    $this->yaxis->Stroke($this->xscale);

	    $myaxis = $this->yaxis;
	    $myaxis->SetPos('max');
	    $myaxis->SetLabelMargin(10);
	    $myaxis->SetLabelSide(SIDE_RIGHT);
	    $myaxis->title->Set('');
	    $myaxis->scale->ticks->SetSide($rightpos);
	    $myaxis->Stroke($this->xscale);
	    
	}
	else {
	    $this->xaxis->Stroke($this->yscale,$aStrokeLabels);
	    $this->yaxis->Stroke($this->xscale,$aStrokeLabels);		
	}
    }


    // Private helper function for backgound image
    function LoadBkgImage($aImgFormat='',$aFile='',$aImgStr='') {
	if( $aImgStr != '' ) {
	    return Image::CreateFromString($aImgStr);
	}
	if( $aFile == '' )
	    $aFile = $this->background_image;
	// Remove case sensitivity and setup appropriate function to create image
	// Get file extension. This should be the LAST '.' separated part of the filename
	$e = explode('.',$aFile);
	$ext = strtolower($e[count($e)-1]);
	if ($ext == "jpeg")  {
	    $ext = "jpg";
	}
	
	if( trim($ext) == '' ) 
	    $ext = 'png';  // Assume PNG if no extension specified

	if( $aImgFormat == '' )
	    $imgtag = $ext;
	else
	    $imgtag = $aImgFormat;

	$supported = imagetypes();
	if( ( $ext == 'jpg' && !($supported & IMG_JPG) ) ||
	    ( $ext == 'gif' && !($supported & IMG_GIF) ) ||
	    ( $ext == 'png' && !($supported & IMG_PNG) ) ) {
	    JpGraphError::RaiseL(25037,$aFile);//('The image format of your background image ('.$aFile.') is not supported in your system configuration. ');
	}


	if( $imgtag == "jpg" || $imgtag == "jpeg")
	{
	    $f = "imagecreatefromjpeg";
	    $imgtag = "jpg";
	}
	else
	{
	    $f = "imagecreatefrom".$imgtag;
	}

	// Compare specified image type and file extension
	if( $imgtag != $ext ) {
	    //$t = "Background image seems to be of different type (has different file extension) than specified imagetype. Specified: '".$aImgFormat."'File: '".$aFile."'";
	    JpGraphError::RaiseL(25038, $aImgFormat, $aFile);
	}

	$img = @$f($aFile);
	if( !$img ) {
	    JpGraphError::RaiseL(25039,$aFile);//(" Can't read background image: '".$aFile."'");   
	}
	return $img;
    }	

    function StrokeBackgroundGrad() {
	if( $this->bkg_gradtype < 0  ) 
	    return;
	$grad = new Gradient($this->img);
	if( $this->bkg_gradstyle == BGRAD_PLOT ) {
	    $xl = $this->img->left_margin;
	    $yt = $this->img->top_margin;
	    $xr = $xl + $this->img->plotwidth+1 ;
	    $yb = $yt + $this->img->plotheight ;
	    $grad->FilledRectangle($xl,$yt,$xr,$yb,$this->bkg_gradfrom,$this->bkg_gradto,$this->bkg_gradtype);
	}
	else {
	    $xl = 0;
	    $yt = 0;
	    $xr = $xl + $this->img->width - 1;
	    $yb = $yt + $this->img->height;
	    if( $this->doshadow  ) {
		$xr -= $this->shadow_width; 
		$yb -= $this->shadow_width; 
	    }
	    if( $this->doframe ) {
		$yt += $this->frame_weight;
		$yb -= $this->frame_weight;
		$xl += $this->frame_weight;
		$xr -= $this->frame_weight;
	    }
	    $aa = $this->img->SetAngle(0);
	    $grad->FilledRectangle($xl,$yt,$xr,$yb,$this->bkg_gradfrom,$this->bkg_gradto,$this->bkg_gradtype);
	    $aa = $this->img->SetAngle($aa);
	}
    }

    function StrokeFrameBackground() {
	if( $this->background_image != "" && $this->background_cflag != "" ) {
	    JpGraphError::RaiseL(25040);//('It is not possible to specify both a background image and a background country flag.');
	}
	if( $this->background_image != "" ) {
	    $bkgimg = $this->LoadBkgImage($this->background_image_format);
	    $this->img->_AdjBrightContrast($bkgimg,$this->background_image_bright,
					   $this->background_image_contr);
	    $this->img->_AdjSat($bkgimg,$this->background_image_sat);
	}
	elseif( $this->background_cflag != "" ) {
	    if( ! class_exists('FlagImages') ) {
		JpGraphError::RaiseL(25041);//('In order to use Country flags as backgrounds you must include the "jpgraph_flags.php" file.');
	    }
	    $fobj = new FlagImages(FLAGSIZE4);
	    $dummy='';
	    $bkgimg = $fobj->GetImgByName($this->background_cflag,$dummy);
	    $this->background_image_mix = $this->background_cflag_mix;
	    $this->background_image_type = $this->background_cflag_type;
	}
	else {
	    return ;
	}

	$bw = ImageSX($bkgimg);
	$bh = ImageSY($bkgimg);

	// No matter what the angle is we always stroke the image and frame
	// assuming it is 0 degree
	$aa = $this->img->SetAngle(0);
		
	switch( $this->background_image_type ) {
	    case BGIMG_FILLPLOT: // Resize to just fill the plotarea
		$this->FillMarginArea();
		$this->StrokeFrame();
		$this->FillPlotArea();
		$this->img->CopyMerge($bkgimg,
				 $this->img->left_margin,$this->img->top_margin,
				 0,0,$this->img->plotwidth+1,$this->img->plotheight,
				 $bw,$bh,$this->background_image_mix);
		break;
	    case BGIMG_FILLFRAME: // Fill the whole area from upper left corner, resize to just fit
		$hadj=0; $vadj=0;
		if( $this->doshadow ) {
		    $hadj = $this->shadow_width;
		    $vadj = $this->shadow_width;
		}
		$this->FillMarginArea();
		$this->FillPlotArea();
		$this->img->CopyMerge($bkgimg,0,0,0,0,$this->img->width-$hadj,$this->img->height-$vadj,
				      $bw,$bh,$this->background_image_mix);
		$this->StrokeFrame();
		break;
	    case BGIMG_COPY: // Just copy the image from left corner, no resizing
		$this->FillMarginArea();
		$this->FillPlotArea();
		$this->img->CopyMerge($bkgimg,0,0,0,0,$bw,$bh,
				      $bw,$bh,$this->background_image_mix);
		$this->StrokeFrame();
		break;
	    case BGIMG_CENTER: // Center original image in the plot area
		$this->FillMarginArea();
		$this->FillPlotArea();
		$centerx = round($this->img->plotwidth/2+$this->img->left_margin-$bw/2);
		$centery = round($this->img->plotheight/2+$this->img->top_margin-$bh/2);
		$this->img->CopyMerge($bkgimg,$centerx,$centery,0,0,$bw,$bh,
				      $bw,$bh,$this->background_image_mix);
		$this->StrokeFrame();
		break;
	    default:
		JpGraphError::RaiseL(25042);//(" Unknown background image layout");
	}			
	$this->img->SetAngle($aa);		
    }

    // Private
    // Draw a frame around the image
    function StrokeFrame() {
	if( !$this->doframe ) return;

	if( $this->background_image_type <= 1 && 
	    ($this->bkg_gradtype < 0 || ($this->bkg_gradtype > 0 && $this->bkg_gradstyle==BGRAD_PLOT)) ) { 
	    $c = $this->margin_color;
	}
	else {
	    $c = false;
	}
	
	if( $this->doshadow ) {
	    $this->img->SetColor($this->frame_color);			
	    $this->img->ShadowRectangle(0,0,$this->img->width,$this->img->height,
					$c,$this->shadow_width,$this->shadow_color);
	}
	elseif( $this->framebevel ) {
	    if( $c ) {
		$this->img->SetColor($this->margin_color);
		$this->img->FilledRectangle(0,0,$this->img->width-1,$this->img->height-1); 
	    }
	    $this->img->Bevel(1,1,$this->img->width-2,$this->img->height-2,
			      $this->framebeveldepth,
			      $this->framebevelcolor1,$this->framebevelcolor2);
	    if( $this->framebevelborder ) {
		$this->img->SetColor($this->framebevelbordercolor);
		$this->img->Rectangle(0,0,$this->img->width-1,$this->img->height-1);
	    }
	}
	else {
	    $this->img->SetLineWeight($this->frame_weight);
	    if( $c ) {
		$this->img->SetColor($this->margin_color);
		$this->img->FilledRectangle(0,0,$this->img->width-1,$this->img->height-1); 
	    }
	    $this->img->SetColor($this->frame_color);
	    $this->img->Rectangle(0,0,$this->img->width-1,$this->img->height-1);		
	}
    }

    function FillMarginArea() {
	$hadj=0; $vadj=0;
	if( $this->doshadow ) {
	    $hadj = $this->shadow_width;
	    $vadj = $this->shadow_width;
	}

	$this->img->SetColor($this->margin_color);
//	$this->img->FilledRectangle(0,0,$this->img->width-1-$hadj,$this->img->height-1-$vadj); 

	$this->img->FilledRectangle(0,0,$this->img->width-1-$hadj,$this->img->top_margin); 
	$this->img->FilledRectangle(0,$this->img->top_margin,$this->img->left_margin,$this->img->height-1-$hadj); 
	$this->img->FilledRectangle($this->img->left_margin+1,
				    $this->img->height-$this->img->bottom_margin,
				    $this->img->width-1-$hadj,
				    $this->img->height-1-$hadj); 
	$this->img->FilledRectangle($this->img->width-$this->img->right_margin,
				    $this->img->top_margin+1,
				    $this->img->width-1-$hadj,
				    $this->img->height-$this->img->bottom_margin-1); 
    }

    function FillPlotArea() {
	$this->img->PushColor($this->plotarea_color);
	$this->img->FilledRectangle($this->img->left_margin,
				    $this->img->top_margin,
				    $this->img->width-$this->img->right_margin,
				    $this->img->height-$this->img->bottom_margin);	
	$this->img->PopColor();
    }
    
    // Stroke the plot area with either a solid color or a background image
    function StrokePlotArea() {
	// Note: To be consistent we really should take a possible shadow
	// into account. However, that causes some problem for the LinearScale class
	// since in the current design it does not have any links to class Graph which
	// means it has no way of compensating for the adjusted plotarea in case of a 
	// shadow. So, until I redesign LinearScale we can't compensate for this.
	// So just set the two adjustment parameters to zero for now.
	$boxadj = 0; //$this->doframe ? $this->frame_weight : 0 ;
	$adj = 0; //$this->doshadow ? $this->shadow_width : 0 ;

	if( $this->background_image != "" || $this->background_cflag != "" ) {
	    $this->StrokeFrameBackground();
	}
	else {
	    $aa = $this->img->SetAngle(0);
	    $this->StrokeFrame();
	    $aa = $this->img->SetAngle($aa);
	    $this->StrokeBackgroundGrad();
	    if( $this->bkg_gradtype < 0 || 
		($this->bkg_gradtype > 0 && $this->bkg_gradstyle==BGRAD_MARGIN) ) {
		$this->FillPlotArea();
	    }
	}	
    }	

    function StrokeIcons() {
	$n = count($this->iIcons);
	for( $i=0; $i < $n; ++$i ) {
	    $this->iIcons[$i]->StrokeWithScale($this->img,$this->xscale,$this->yscale);
	}
    }
	
    function StrokePlotBox() {
	// Should we draw a box around the plot area?
	if( $this->boxed ) {
	    $this->img->SetLineWeight(1);
	    $this->img->SetLineStyle('solid');
	    $this->img->SetColor($this->box_color);
	    for($i=0; $i < $this->box_weight; ++$i ) {
		$this->img->Rectangle(
		    $this->img->left_margin-$i,$this->img->top_margin-$i,
		    $this->img->width-$this->img->right_margin+$i,
		    $this->img->height-$this->img->bottom_margin+$i);
	    }
	}						
    }		

    function SetTitleBackgroundFillStyle($aStyle,$aColor1='black',$aColor2='white') {
	$this->titlebkg_fillstyle = $aStyle;
	$this->titlebkg_scolor1 = $aColor1;
	$this->titlebkg_scolor2 = $aColor2;
    }

    function SetTitleBackground($aBackColor='gray', $aStyle=TITLEBKG_STYLE1, $aFrameStyle=TITLEBKG_FRAME_NONE, $aFrameColor='black', $aFrameWeight=1, $aBevelHeight=3, $aEnable=true) {
	$this->titlebackground = $aEnable;
	$this->titlebackground_color = $aBackColor;
	$this->titlebackground_style = $aStyle;
	$this->titlebackground_framecolor = $aFrameColor;
	$this->titlebackground_framestyle = $aFrameStyle;
	$this->titlebackground_frameweight = $aFrameWeight;	
	$this->titlebackground_bevelheight = $aBevelHeight ;
    }


    function StrokeTitles() {

	$margin=3;

	if( $this->titlebackground ) {

	    // Find out height
	    $this->title->margin += 2 ;
	    $h = $this->title->GetTextHeight($this->img)+$this->title->margin+$margin;
	    if( $this->subtitle->t != "" && !$this->subtitle->hide ) {
		$h += $this->subtitle->GetTextHeight($this->img)+$margin+
		    $this->subtitle->margin;
		$h += 2;
	    }
	    if( $this->subsubtitle->t != "" && !$this->subsubtitle->hide ) {
		$h += $this->subsubtitle->GetTextHeight($this->img)+$margin+
		    $this->subsubtitle->margin;
		$h += 2;
	    }
	    $this->img->PushColor($this->titlebackground_color);
	    if( $this->titlebackground_style === TITLEBKG_STYLE1 ) {
		// Inside the frame
		if( $this->framebevel ) {
		    $x1 = $y1 = $this->framebeveldepth + 1 ;
		    $x2 = $this->img->width - $this->framebeveldepth - 2 ; 
		    $this->title->margin += $this->framebeveldepth + 1 ;
		    $h += $y1 ;
		    $h += 2;
		}
		else {
		    $x1 = $y1 = $this->frame_weight;
		    $x2 = $this->img->width - 2*$x1;
		}
	    }
	    elseif( $this->titlebackground_style === TITLEBKG_STYLE2 ) {
		// Cover the frame as well
		$x1 = $y1 = 0;
		$x2 = $this->img->width - 1 ;
	    }
	    elseif( $this->titlebackground_style === TITLEBKG_STYLE3 ) {
		// Cover the frame as well (the difference is that
		// for style==3 a bevel frame border is on top
		// of the title background)
		$x1 = $y1 = 0;
		$x2 = $this->img->width - 1 ;
		$h += $this->framebeveldepth ;
		$this->title->margin += $this->framebeveldepth ;
	    }
	    else {
		JpGraphError::RaiseL(25043);//('Unknown title background style.');
	    }

	    if( $this->titlebackground_framestyle === 3 ) {
		$h += $this->titlebackground_bevelheight*2 + 1  ;
		$this->title->margin += $this->titlebackground_bevelheight ;
	    }

	    if( $this->doshadow ) {
		$x2 -= $this->shadow_width ;
	    }
	    
	    $indent=0;
	    if( $this->titlebackground_framestyle == TITLEBKG_FRAME_BEVEL ) {
		$ind = $this->titlebackground_bevelheight;
	    }

	    if( $this->titlebkg_fillstyle==TITLEBKG_FILLSTYLE_HSTRIPED ) {
		$this->img->FilledRectangle2($x1+$ind,$y1+$ind,$x2-$ind,$h-$ind,
					     $this->titlebkg_scolor1,
					     $this->titlebkg_scolor2);
	    }
	    elseif( $this->titlebkg_fillstyle==TITLEBKG_FILLSTYLE_VSTRIPED ) {
		$this->img->FilledRectangle2($x1+$ind,$y1+$ind,$x2-$ind,$h-$ind,
					     $this->titlebkg_scolor1,
					     $this->titlebkg_scolor2,2);
	    }
	    else {
		// Solid fill
		$this->img->FilledRectangle($x1,$y1,$x2,$h);
	    }
	    $this->img->PopColor();

	    $this->img->PushColor($this->titlebackground_framecolor);
	    $this->img->SetLineWeight($this->titlebackground_frameweight);
	    if( $this->titlebackground_framestyle == TITLEBKG_FRAME_FULL ) {
		// Frame background
		$this->img->Rectangle($x1,$y1,$x2,$h);
	    }
	    elseif( $this->titlebackground_framestyle == TITLEBKG_FRAME_BOTTOM ) {
		// Bottom line only
		$this->img->Line($x1,$h,$x2,$h);
	    }
	    elseif( $this->titlebackground_framestyle == TITLEBKG_FRAME_BEVEL ) {
		$this->img->Bevel($x1,$y1,$x2,$h,$this->titlebackground_bevelheight);
	    }
	    $this->img->PopColor();

	    // This is clumsy. But we neeed to stroke the whole graph frame if it is
	    // set to bevel to get the bevel shading on top of the text background
	    if( $this->framebevel && $this->doframe && 
		$this->titlebackground_style === 3 ) {
		$this->img->Bevel(1,1,$this->img->width-2,$this->img->height-2,
				  $this->framebeveldepth,
				  $this->framebevelcolor1,$this->framebevelcolor2);
		if( $this->framebevelborder ) {
		    $this->img->SetColor($this->framebevelbordercolor);
		    $this->img->Rectangle(0,0,$this->img->width-1,$this->img->height-1);
		}
	    }
	}

	// Stroke title
	$y = $this->title->margin; 
	if( $this->title->halign == 'center' ) 
	    $this->title->Center(0,$this->img->width,$y);
	elseif( $this->title->halign == 'left' ) {
	    $this->title->SetPos($this->title->margin+2,$y);
	}
	elseif( $this->title->halign == 'right' ) {
	    $indent = 0;
	    if( $this->doshadow ) 
		$indent = $this->shadow_width+2;
	    $this->title->SetPos($this->img->width-$this->title->margin-$indent,$y,'right');	    
	}
	$this->title->Stroke($this->img);
		
	// ... and subtitle
	$y += $this->title->GetTextHeight($this->img) + $margin + $this->subtitle->margin;
	if( $this->subtitle->halign == 'center' ) 
	    $this->subtitle->Center(0,$this->img->width,$y);
	elseif( $this->subtitle->halign == 'left' ) {
	    $this->subtitle->SetPos($this->subtitle->margin+2,$y);
	}
	elseif( $this->subtitle->halign == 'right' ) {
	    $indent = 0;
	    if( $this->doshadow ) 
		$indent = $this->shadow_width+2;
	    $this->subtitle->SetPos($this->img->width-$this->subtitle->margin-$indent,$y,'right'); 
	}
	$this->subtitle->Stroke($this->img);

	// ... and subsubtitle
	$y += $this->subtitle->GetTextHeight($this->img) + $margin + $this->subsubtitle->margin;
	if( $this->subsubtitle->halign == 'center' ) 
	    $this->subsubtitle->Center(0,$this->img->width,$y);
	elseif( $this->subsubtitle->halign == 'left' ) {
	    $this->subsubtitle->SetPos($this->subsubtitle->margin+2,$y);
	}
	elseif( $this->subsubtitle->halign == 'right' ) {
	    $indent = 0;
	    if( $this->doshadow ) 
		$indent = $this->shadow_width+2;
	    $this->subsubtitle->SetPos($this->img->width-$this->subsubtitle->margin-$indent,$y,'right'); 
	}
	$this->subsubtitle->Stroke($this->img);

	// ... and fancy title
	$this->tabtitle->Stroke($this->img);

    }

    function StrokeTexts() {
	// Stroke any user added text objects
	if( $this->texts != null ) {
	    for($i=0; $i < count($this->texts); ++$i) {
		$this->texts[$i]->StrokeWithScale($this->img,$this->xscale,$this->yscale);
	    }
	}

	if( $this->y2texts != null && $this->y2scale != null ) {
	    for($i=0; $i < count($this->y2texts); ++$i) {
		$this->y2texts[$i]->StrokeWithScale($this->img,$this->xscale,$this->y2scale);
	    }
	}

    }

    function StrokeTables() {
	if( $this->iTables != null ) {
	    $n = count($this->iTables);
	    for( $i=0; $i < $n; ++$i ) {
		$this->iTables[$i]->StrokeWithScale($this->img,$this->xscale,$this->yscale);
	    }
	}
    }

    function DisplayClientSideaImageMapAreas() {
	// Debug stuff - display the outline of the image map areas
	$csim='';
	foreach ($this->plots as $p) {
	    $csim.= $p->GetCSIMareas();
	}
	$csim .= $this->legend->GetCSIMareas();
	if (preg_match_all("/area shape=\"(\w+)\" coords=\"([0-9\, ]+)\"/", $csim, $coords)) {
	    $this->img->SetColor($this->csimcolor);
	    $n = count($coords[0]);
	    for ($i=0; $i < $n; $i++) {
		if ($coords[1][$i]=="poly") {
		    preg_match_all('/\s*([0-9]+)\s*,\s*([0-9]+)\s*,*/',$coords[2][$i],$pts);
		    $this->img->SetStartPoint($pts[1][count($pts[0])-1],$pts[2][count($pts[0])-1]);
		    $m = count($pts[0]);
		    for ($j=0; $j < $m; $j++) {
			$this->img->LineTo($pts[1][$j],$pts[2][$j]);
		    }
		} else if ($coords[1][$i]=="rect") {
		    $pts = preg_split('/,/', $coords[2][$i]);
		    $this->img->SetStartPoint($pts[0],$pts[1]);
		    $this->img->LineTo($pts[2],$pts[1]);
		    $this->img->LineTo($pts[2],$pts[3]);
		    $this->img->LineTo($pts[0],$pts[3]);
		    $this->img->LineTo($pts[0],$pts[1]);					
		}
	    }
	}
    }

    function AdjustSaturationBrightnessContrast() {
	// Adjust the brightness and contrast of the image
	if( $this->image_contr || $this->image_bright )
	    $this->img->AdjBrightContrast($this->image_bright,$this->image_contr);
	if( $this->image_sat )											 
	    $this->img->AdjSat($this->image_sat);
    }

    // Text scale offset in fractions of a major scale step
    function SetTextScaleOff($aOff) {
	$this->text_scale_off = $aOff;
	$this->xscale->text_scale_off = $aOff;
    }

    // Text width of bar to be centered in absolute pixels
    function SetTextScaleAbsCenterOff($aOff) {
	$this->text_scale_abscenteroff = $aOff;
    }

    // Get Y min and max values for added lines
    function GetLinesYMinMax( $aLines ) {
	$n = count($aLines);
	if( $n == 0 ) return false;
	$min = $aLines[0]->scaleposition ;
	$max = $min ;
	$flg = false;
	for( $i=0; $i < $n; ++$i ) {
	    if( $aLines[$i]->direction == HORIZONTAL ) {
		$flg = true ;
		$v = $aLines[$i]->scaleposition ;
		if( $min > $v ) $min = $v ;
		if( $max < $v ) $max = $v ;
	    }
	}
	return $flg ? array($min,$max) : false ;
    }

    // Get X min and max values for added lines
    function GetLinesXMinMax( $aLines ) {
	$n = count($aLines);
	if( $n == 0 ) return false ;
	$min = $aLines[0]->scaleposition ;
	$max = $min ;
	$flg = false;
	for( $i=0; $i < $n; ++$i ) {
	    if( $aLines[$i]->direction == VERTICAL ) {
		$flg = true ;
		$v = $aLines[$i]->scaleposition ;
		if( $min > $v ) $min = $v ;
		if( $max < $v ) $max = $v ;
	    }
	}
	return $flg ? array($min,$max) : false ;
    }

    // Get min and max values for all included plots
    function GetPlotsYMinMax(&$aPlots) {
	$n = count($aPlots);
	$i=0;
	do {
	    list($xmax,$max) = $aPlots[$i]->Max();
	} while( ++$i < $n && !is_numeric($max) );
	
	$i=0;
	do {
           list($xmin,$min) = $aPlots[$i]->Min();
       } while( ++$i < $n && !is_numeric($min) );
	
	if( !is_numeric($min) || !is_numeric($max) ) {
	    JpGraphError::RaiseL(25044);//('Cannot use autoscaling since it is impossible to determine a valid min/max value  of the Y-axis (only null values).');
	}

	list($xmax,$max) = $aPlots[0]->Max();
	list($xmin,$min) = $aPlots[0]->Min();
	for($i=0; $i < count($aPlots); ++$i ) {
	    list($xmax,$ymax)=$aPlots[$i]->Max();
	    list($xmin,$ymin)=$aPlots[$i]->Min();
	    if (is_numeric($ymax)) $max=max($max,$ymax);
	    if (is_numeric($ymin)) $min=min($min,$ymin);
	}
	if( $min == '' ) $min = 0;
	if( $max == '' ) $max = 0;
	if( $min == 0 && $max == 0 ) {
	    // Special case if all values are 0
	    $min=0;$max=1;			
	}
	return array($min,$max);
    }

} // Class


//===================================================
// CLASS TTF
// Description: Handle TTF font names
//===================================================
class TTF {
    var $font_files,$style_names;
//---------------
// CONSTRUCTOR
    function TTF() {
	$this->style_names=array(FS_NORMAL=>'normal',FS_BOLD=>'bold',FS_ITALIC=>'italic',FS_BOLDITALIC=>'bolditalic');
	// File names for available fonts
	$this->font_files=array(
	    FF_COURIER => array(FS_NORMAL=>'cour.ttf', FS_BOLD=>'courbd.ttf', FS_ITALIC=>'couri.ttf', FS_BOLDITALIC=>'courbi.ttf' ),
	    FF_GEORGIA => array(FS_NORMAL=>'georgia.ttf', FS_BOLD=>'georgiab.ttf', FS_ITALIC=>'georgiai.ttf', FS_BOLDITALIC=>'' ),
	    FF_TREBUCHE =>array(FS_NORMAL=>'trebuc.ttf', FS_BOLD=>'trebucbd.ttf',   FS_ITALIC=>'trebucit.ttf', FS_BOLDITALIC=>'trebucbi.ttf' ),
	    FF_VERDANA => array(FS_NORMAL=>'verdana.ttf', FS_BOLD=>'verdanab.ttf',  FS_ITALIC=>'verdanai.ttf', FS_BOLDITALIC=>'' ),
	    FF_TIMES =>   array(FS_NORMAL=>'times.ttf',   FS_BOLD=>'timesbd.ttf',   FS_ITALIC=>'timesi.ttf',   FS_BOLDITALIC=>'timesbi.ttf' ),
	    FF_COMIC =>   array(FS_NORMAL=>'comic.ttf',   FS_BOLD=>'comicbd.ttf',   FS_ITALIC=>'',         FS_BOLDITALIC=>'' ),
	    FF_ARIAL =>   array(FS_NORMAL=>'arial.ttf',   FS_BOLD=>'arialbd.ttf',   FS_ITALIC=>'ariali.ttf',   FS_BOLDITALIC=>'arialbi.ttf' ) ,
	    FF_VERA =>    array(FS_NORMAL=>'Vera.ttf',   FS_BOLD=>'VeraBd.ttf',   FS_ITALIC=>'VeraIt.ttf',   FS_BOLDITALIC=>'VeraBI.ttf' ),
	    FF_VERAMONO => array(FS_NORMAL=>'VeraMono.ttf', FS_BOLD=>'VeraMoBd.ttf', FS_ITALIC=>'VeraMoIt.ttf', FS_BOLDITALIC=>'VeraMoBI.ttf' ),
	    FF_VERASERIF => array(FS_NORMAL=>'VeraSe.ttf', FS_BOLD=>'VeraSeBd.ttf', FS_ITALIC=>'', FS_BOLDITALIC=>'' ) ,
	    FF_SIMSUN =>  array(FS_NORMAL=>'simsun.ttc',  FS_BOLD=>'simhei.ttf',   FS_ITALIC=>'',   FS_BOLDITALIC=>'' ),
	    FF_CHINESE => array(FS_NORMAL=>CHINESE_TTF_FONT, FS_BOLD=>'', FS_ITALIC=>'', FS_BOLDITALIC=>'' ),
 	    FF_MINCHO =>  array(FS_NORMAL=>MINCHO_TTF_FONT,  FS_BOLD=>'',   FS_ITALIC=>'',   FS_BOLDITALIC=>'' ),
 	    FF_PMINCHO => array(FS_NORMAL=>PMINCHO_TTF_FONT,  FS_BOLD=>'',   FS_ITALIC=>'',   FS_BOLDITALIC=>'' ),    
 	    FF_GOTHIC  => array(FS_NORMAL=>GOTHIC_TTF_FONT,  FS_BOLD=>'',   FS_ITALIC=>'',   FS_BOLDITALIC=>'' ),    
 	    FF_PGOTHIC => array(FS_NORMAL=>PGOTHIC_TTF_FONT,  FS_BOLD=>'',   FS_ITALIC=>'',   FS_BOLDITALIC=>'' ),    
 	    FF_MINCHO =>  array(FS_NORMAL=>PMINCHO_TTF_FONT,  FS_BOLD=>'',   FS_ITALIC=>'',   FS_BOLDITALIC=>'' )   
);
    }

//---------------
// PUBLIC METHODS	
    // Create the TTF file from the font specification
    function File($family,$style=FS_NORMAL) {
	
	if( $family == FF_HANDWRT || $family==FF_BOOK ) {
	    JpGraphError::RaiseL(25045);//('Font families FF_HANDWRT and FF_BOOK are no longer available due to copyright problem with these fonts. Fonts can no longer be distributed with JpGraph. Please download fonts from http://corefonts.sourceforge.net/');
	}

	$fam = @$this->font_files[$family];
	if( !$fam ) {
	    JpGraphError::RaiseL(25046,$family);//("Specified TTF font family (id=$family) is unknown or does not exist. Please note that TTF fonts are not distributed with JpGraph for copyright reasons. You can find the MS TTF WEB-fonts (arial, courier etc) for download at http://corefonts.sourceforge.net/");
	}
	$f = @$fam[$style];

	if( $f==='' )
	    JpGraphError::RaiseL(25047,$this->style_names[$style],$this->font_files[$family][FS_NORMAL]);//('Style "'.$this->style_names[$style].'" is not available for font family '.$this->font_files[$family][FS_NORMAL].'.');
	if( !$f ) {
	    JpGraphError::RaiseL(25048,$fam);//("Unknown font style specification [$fam].");
	}

	if ($family >= FF_MINCHO && $family <= FF_PGOTHIC) {
	    $f = MBTTF_DIR.$f;
	} else {
	    $f = TTF_DIR.$f;
	}

	if( file_exists($f) === false || is_readable($f) === false ) {
	    JpGraphError::RaiseL(25049,$f);//("Font file \"$f\" is not readable or does not exist.");
	}
	return $f;
    }
} // Class

//===================================================
// CLASS LineProperty
// Description: Holds properties for a line
//===================================================
class LineProperty {
    var $iWeight=1, $iColor="black",$iStyle="solid";
    var $iShow=true;
	
//---------------
// PUBLIC METHODS	
    function SetColor($aColor) {
	$this->iColor = $aColor;
    }
	
    function SetWeight($aWeight) {
	$this->iWeight = $aWeight;
    }
	
    function SetStyle($aStyle) {
	$this->iStyle = $aStyle;
    }
		
    function Show($aShow=true) {
	$this->iShow=$aShow;
    }
	
    function Stroke(&$aImg,$aX1,$aY1,$aX2,$aY2) {
	if( $this->iShow ) {
	    $aImg->PushColor($this->iColor);
	    $oldls = $aImg->line_style;
	    $oldlw = $aImg->line_weight;
	    $aImg->SetLineWeight($this->iWeight);
	    $aImg->SetLineStyle($this->iStyle);			
	    $aImg->StyleLine($aX1,$aY1,$aX2,$aY2);
	    $aImg->PopColor($this->iColor);
	    $aImg->line_style = $oldls;
	    $aImg->line_weight = $oldlw;

	}
    }
}


//===================================================
// CLASS Text
// Description: Arbitrary text object that can be added to the graph
//===================================================
class Text {
    var $t,$x=0,$y=0,$halign="left",$valign="top",$color=array(0,0,0);
    var $font_family=FF_FONT1,$font_style=FS_NORMAL,$font_size=12;
    var $hide=false, $dir=0;
    var $boxed=false;	// Should the text be boxed
    var $paragraph_align="left";
    var $margin=0;
    var $icornerradius=0,$ishadowwidth=3;
    var $iScalePosY=null,$iScalePosX=null;
    var $iWordwrap=0;
    var $fcolor='white',$bcolor='black',$shadow=false;
    var $iCSIMarea='',$iCSIMalt='',$iCSIMtarget='';

//---------------
// CONSTRUCTOR

    // Create new text at absolute pixel coordinates
    function Text($aTxt="",$aXAbsPos=0,$aYAbsPos=0) {
	if( ! is_string($aTxt) ) {
	    JpGraphError::RaiseL(25050);//('First argument to Text::Text() must be s atring.');
	}
	$this->t = $aTxt;
	$this->x = round($aXAbsPos);
	$this->y = round($aYAbsPos);
	$this->margin = 0;
    }
//---------------
// PUBLIC METHODS	
    // Set the string in the text object
    function Set($aTxt) {
	$this->t = $aTxt;
    }
	
    // Alias for Pos()
    function SetPos($aXAbsPos=0,$aYAbsPos=0,$aHAlign="left",$aVAlign="top") {
	$this->Pos($aXAbsPos,$aYAbsPos,$aHAlign,$aVAlign);
    }
    
    // Specify the position and alignment for the text object
    function Pos($aXAbsPos=0,$aYAbsPos=0,$aHAlign="left",$aVAlign="top") {
	$this->x = $aXAbsPos;
	$this->y = $aYAbsPos;
	$this->halign = $aHAlign;
	$this->valign = $aVAlign;
    }

    function SetScalePos($aX,$aY) {
	$this->iScalePosX = $aX;
	$this->iScalePosY = $aY;
    }
	
    // Specify alignment for the text
    function Align($aHAlign,$aVAlign="top",$aParagraphAlign="") {
	$this->halign = $aHAlign;
	$this->valign = $aVAlign;
	if( $aParagraphAlign != "" )
	    $this->paragraph_align = $aParagraphAlign;
    }		
    
    // Alias
    function SetAlign($aHAlign,$aVAlign="top",$aParagraphAlign="") {
	$this->Align($aHAlign,$aVAlign,$aParagraphAlign);
    }

    // Specifies the alignment for a multi line text
    function ParagraphAlign($aAlign) {
	$this->paragraph_align = $aAlign;
    }

    // Specifies the alignment for a multi line text
    function SetParagraphAlign($aAlign) {
	$this->paragraph_align = $aAlign;
    }

    function SetShadow($aShadowColor='gray',$aShadowWidth=3) {
	$this->ishadowwidth=$aShadowWidth;
	$this->shadow=$aShadowColor;
	$this->boxed=true;
    }

    function SetWordWrap($aCol) {
	$this->iWordwrap = $aCol ;
    }
	
    // Specify that the text should be boxed. fcolor=frame color, bcolor=border color,
    // $shadow=drop shadow should be added around the text.
    function SetBox($aFrameColor=array(255,255,255),$aBorderColor=array(0,0,0),$aShadowColor=false,$aCornerRadius=4,$aShadowWidth=3) {
	if( $aFrameColor==false )
	    $this->boxed=false;
	else
	    $this->boxed=true;
	$this->fcolor=$aFrameColor;
	$this->bcolor=$aBorderColor;
	// For backwards compatibility when shadow was just true or false
	if( $aShadowColor === true )
	    $aShadowColor = 'gray';
	$this->shadow=$aShadowColor;
	$this->icornerradius=$aCornerRadius;
	$this->ishadowwidth=$aShadowWidth;
    }
	
    // Hide the text
    function Hide($aHide=true) {
	$this->hide=$aHide;
    }
	
    // This looks ugly since it's not a very orthogonal design 
    // but I added this "inverse" of Hide() to harmonize
    // with some classes which I designed more recently (especially) 
    // jpgraph_gantt
    function Show($aShow=true) {
	$this->hide=!$aShow;
    }
	
    // Specify font
    function SetFont($aFamily,$aStyle=FS_NORMAL,$aSize=10) {
	$this->font_family=$aFamily;
	$this->font_style=$aStyle;
	$this->font_size=$aSize;
    }
			
    // Center the text between $left and $right coordinates
    function Center($aLeft,$aRight,$aYAbsPos=false) {
	$this->x = $aLeft + ($aRight-$aLeft	)/2;
	$this->halign = "center";
	if( is_numeric($aYAbsPos) )
	    $this->y = $aYAbsPos;		
    }
	
    // Set text color
    function SetColor($aColor) {
	$this->color = $aColor;
    }
	
    function SetAngle($aAngle) {
	$this->SetOrientation($aAngle);
    }
	
    // Orientation of text. Note only TTF fonts can have an arbitrary angle
    function SetOrientation($aDirection=0) {
	if( is_numeric($aDirection) )
	    $this->dir=$aDirection;	
	elseif( $aDirection=="h" )
	    $this->dir = 0;
	elseif( $aDirection=="v" )
	    $this->dir = 90;
	else JpGraphError::RaiseL(25051);//(" Invalid direction specified for text.");
    }
	
    // Total width of text
    function GetWidth(&$aImg) {
	$aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
	$w = $aImg->GetTextWidth($this->t,$this->dir);
	return $w;	
    }
	
    // Hight of font
    function GetFontHeight(&$aImg) {
	$aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
	$h = $aImg->GetFontHeight();
	return $h;

    }

    function GetTextHeight(&$aImg) {
	$aImg->SetFont($this->font_family,$this->font_style,$this->font_size);	
	$h = $aImg->GetTextHeight($this->t,$this->dir);
	return $h;
    }

    function GetHeight(&$aImg) {
	// Synonym for GetTextHeight()
	$aImg->SetFont($this->font_family,$this->font_style,$this->font_size);	
	$h = $aImg->GetTextHeight($this->t,$this->dir);
	return $h;
    }

    // Set the margin which will be interpretated differently depending
    // on the context.
    function SetMargin($aMarg) {
	$this->margin = $aMarg;
    }

    function StrokeWithScale(&$aImg,$axscale,$ayscale) {
	if( $this->iScalePosX === null ||
	    $this->iScalePosY === null ) {
	    $this->Stroke($aImg);
	}
	else {
	    $this->Stroke($aImg,
			  round($axscale->Translate($this->iScalePosX)),
			  round($ayscale->Translate($this->iScalePosY)));
	}
    }

    function SetCSIMTarget($aTarget,$aAlt=null) {
	$this->iCSIMtarget = $aTarget;
	$this->iCSIMalt = $aAlt;
    }

    function GetCSIMareas() {
	if( $this->iCSIMtarget !== '' ) 
	    return $this->iCSIMarea;
	else
	    return '';
    }

    // Display text in image
    function Stroke(&$aImg,$x=null,$y=null) {

	if( !empty($x) ) $this->x = round($x);
	if( !empty($y) ) $this->y = round($y);

	// Insert newlines
	if( $this->iWordwrap > 0 ) {
	    $this->t = wordwrap($this->t,$this->iWordwrap,"\n");
	}

	// If position been given as a fraction of the image size
	// calculate the absolute position
	if( $this->x < 1 && $this->x > 0 ) $this->x *= $aImg->width;
	if( $this->y < 1 && $this->y > 0 ) $this->y *= $aImg->height;

	$aImg->PushColor($this->color);	
	$aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
	$aImg->SetTextAlign($this->halign,$this->valign);
	if( $this->boxed ) {
	    if( $this->fcolor=="nofill" ) 
		$this->fcolor=false;		
	    $aImg->SetLineWeight(1);
	    $bbox = $aImg->StrokeBoxedText($this->x,$this->y,$this->t,
				   $this->dir,$this->fcolor,$this->bcolor,$this->shadow,
				   $this->paragraph_align,5,5,$this->icornerradius,
				   $this->ishadowwidth);
	}
	else {
	    $bbox = $aImg->StrokeText($this->x,$this->y,$this->t,$this->dir,$this->paragraph_align);
	}

	// Create CSIM targets
	$coords = $bbox[0].','.$bbox[1].','.$bbox[2].','.$bbox[3].','.$bbox[4].','.$bbox[5].','.$bbox[6].','.$bbox[7];
	$this->iCSIMarea = "<area shape=\"poly\" coords=\"$coords\" href=\"".$this->iCSIMtarget."\"";
	$this->iCSIMarea .= " alt=\"".$this->iCSIMalt."\" title=\"".$this->iCSIMalt."\" />\n";

	$aImg->PopColor($this->color);	

    }
} // Class

class GraphTabTitle extends Text{
    var $corner = 6 , $posx = 7, $posy = 4;
    var $color='darkred',$fillcolor='lightyellow',$bordercolor='black';
    var $align = 'left', $width=TABTITLE_WIDTHFIT;
    function GraphTabTitle() {
	$this->t = '';
	$this->font_style = FS_BOLD;
	$this->hide = true;
    }

    function SetColor($aTxtColor,$aFillColor='lightyellow',$aBorderColor='black') {
	$this->color = $aTxtColor;
	$this->fillcolor = $aFillColor;
	$this->bordercolor = $aBorderColor;
    }

    function SetFillColor($aFillColor) {
	$this->fillcolor = $aFillColor;
    }

    function SetTabAlign($aAlign) {
	// Synonym for SetPos
	$this->align = $aAlign;
    }

    function SetPos($aAlign) {
	$this->align = $aAlign;
    }
    
    function SetWidth($aWidth) {
	$this->width = $aWidth ;
    }

    function Set($t) {
	$this->t = $t;
	$this->hide = false;
    }

    function SetCorner($aD) {
	$this->corner = $aD ;
    }

    function Stroke(&$aImg) {
	if( $this->hide ) 
	    return;
	$this->boxed = false;
	$w = $this->GetWidth($aImg) + 2*$this->posx;
	$h = $this->GetTextHeight($aImg) + 2*$this->posy;

	$x = $aImg->left_margin;
	$y = $aImg->top_margin;

	if( $this->width === TABTITLE_WIDTHFIT ) {
	    if( $this->align == 'left' ) {
		$p = array($x,                $y,
			   $x,                $y-$h+$this->corner,
			   $x + $this->corner,$y-$h,
			   $x + $w - $this->corner, $y-$h,
			   $x + $w, $y-$h+$this->corner,
			   $x + $w, $y);
	    }
	    elseif( $this->align == 'center' ) {
		$x += round($aImg->plotwidth/2) - round($w/2);
		$p = array($x, $y,
			   $x, $y-$h+$this->corner,
			   $x + $this->corner, $y-$h,
			   $x + $w - $this->corner, $y-$h,
			   $x + $w, $y-$h+$this->corner,
			   $x + $w, $y);
	    }
	    else {
		$x += $aImg->plotwidth -$w;
		$p = array($x, $y,
			   $x, $y-$h+$this->corner,
			   $x + $this->corner,$y-$h,
			   $x + $w - $this->corner, $y-$h,
			   $x + $w, $y-$h+$this->corner,
			   $x + $w, $y);
	    }
	}
	else {
	    if( $this->width === TABTITLE_WIDTHFULL )
		$w = $aImg->plotwidth ;
	    else
		$w = $this->width ;

	    // Make the tab fit the width of the plot area
	    $p = array($x,                $y,
		       $x,                $y-$h+$this->corner,
		       $x + $this->corner,$y-$h,
		       $x + $w - $this->corner, $y-$h,
		       $x + $w, $y-$h+$this->corner,
		       $x + $w, $y);
	    
	}
	if( $this->halign == 'left' ) {
	    $aImg->SetTextAlign('left','bottom');
	    $x += $this->posx;
	    $y -= $this->posy;
	}
	elseif( $this->halign == 'center' ) {
	    $aImg->SetTextAlign('center','bottom');
	    $x += $w/2; 
	    $y -= $this->posy;
	}
	else {
	    $aImg->SetTextAlign('right','bottom');
	    $x += $w - $this->posx;
	    $y -= $this->posy;
	}

	$aImg->SetColor($this->fillcolor);
	$aImg->FilledPolygon($p);

	$aImg->SetColor($this->bordercolor);
	$aImg->Polygon($p,true);
	
	$aImg->SetColor($this->color);
	$aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
	$aImg->StrokeText($x,$y,$this->t,0,'center');
    }

}

//===================================================
// CLASS SuperScriptText
// Description: Format a superscript text
//===================================================
class SuperScriptText extends Text {
    var $iSuper="";
    var $sfont_family="",$sfont_style="",$sfont_size=8;
    var $iSuperMargin=2,$iVertOverlap=4,$iSuperScale=0.65;
    var $iSDir=0;
    var $iSimple=false;

    function SuperScriptText($aTxt="",$aSuper="",$aXAbsPos=0,$aYAbsPos=0) {
	parent::Text($aTxt,$aXAbsPos,$aYAbsPos);
	$this->iSuper = $aSuper;
    }

    function FromReal($aVal,$aPrecision=2) {
	// Convert a floating point number to scientific notation
	$neg=1.0;
	if( $aVal < 0 ) {
	    $neg = -1.0;
	    $aVal = -$aVal;
	}
		
	$l = floor(log10($aVal));
	$a = sprintf("%0.".$aPrecision."f",round($aVal / pow(10,$l),$aPrecision));
	$a *= $neg;
	if( $this->iSimple && ($a == 1 || $a==-1) ) $a = '';
	
	if( $a != '' )
	    $this->t = $a.' * 10';
	else {
	    if( $neg == 1 )
		$this->t = '10';
	    else
		$this->t = '-10';
	}
	$this->iSuper = $l;
    }

    function Set($aTxt,$aSuper="") {
	$this->t = $aTxt;
	$this->iSuper = $aSuper;
    }

    function SetSuperFont($aFontFam,$aFontStyle=FS_NORMAL,$aFontSize=8) {
	$this->sfont_family = $aFontFam;
	$this->sfont_style = $aFontStyle;
	$this->sfont_size = $aFontSize;
    }

    // Total width of text
    function GetWidth(&$aImg) {
	$aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
	$w = $aImg->GetTextWidth($this->t);
	$aImg->SetFont($this->sfont_family,$this->sfont_style,$this->sfont_size);
	$w += $aImg->GetTextWidth($this->iSuper);
	$w += $this->iSuperMargin;
	return $w;
    }
	
    // Hight of font (approximate the height of the text)
    function GetFontHeight(&$aImg) {
	$aImg->SetFont($this->font_family,$this->font_style,$this->font_size);	
	$h = $aImg->GetFontHeight();
	$aImg->SetFont($this->sfont_family,$this->sfont_style,$this->sfont_size);
	$h += $aImg->GetFontHeight();
	return $h;
    }

    // Hight of text
    function GetTextHeight(&$aImg) {
	$aImg->SetFont($this->font_family,$this->font_style,$this->font_size);
	$h = $aImg->GetTextHeight($this->t);
	$aImg->SetFont($this->sfont_family,$this->sfont_style,$this->sfont_size);
	$h += $aImg->GetTextHeight($this->iSuper);
	return $h;
    }

    function Stroke(&$aImg,$ax=-1,$ay=-1) {
	
        // To position the super script correctly we need different
	// cases to handle the alignmewnt specified since that will
	// determine how we can interpret the x,y coordinates
	
	$w = parent::GetWidth($aImg);
	$h = parent::GetTextHeight($aImg);
	switch( $this->valign ) {
	    case 'top':
		$sy = $this->y;
		break;
	    case 'center':
		$sy = $this->y - $h/2;
		break;
	    case 'bottom':
		$sy = $this->y - $h;
		break;
	    default:
		JpGraphError::RaiseL(25052);//('PANIC: Internal error in SuperScript::Stroke(). Unknown vertical alignment for text');
		exit();
	}

	switch( $this->halign ) {
	    case 'left':
		$sx = $this->x + $w;
		break;
	    case 'center':
		$sx = $this->x + $w/2;
		break;
	    case 'right':
		$sx = $this->x;
		break;
	    default:
		JpGraphError::RaiseL(25053);//('PANIC: Internal error in SuperScript::Stroke(). Unknown horizontal alignment for text');
		exit();
	}

	$sx += $this->iSuperMargin;
	$sy += $this->iVertOverlap;

	// Should we automatically determine the font or
	// has the user specified it explicetly?
	if( $this->sfont_family == "" ) {
	    if( $this->font_family <= FF_FONT2 ) {
		if( $this->font_family == FF_FONT0 ) {
		    $sff = FF_FONT0;
		}
		elseif( $this->font_family == FF_FONT1 ) {
		    if( $this->font_style == FS_NORMAL )
			$sff = FF_FONT0;
		    else
			$sff = FF_FONT1;
		}
		else {
		    $sff = FF_FONT1;
		}
		$sfs = $this->font_style;
		$sfz = $this->font_size;
	    }
	    else {
		// TTF fonts
		$sff = $this->font_family;
		$sfs = $this->font_style;
		$sfz = floor($this->font_size*$this->iSuperScale);		
		if( $sfz < 8 ) $sfz = 8;
	    }	    
	    $this->sfont_family = $sff;
	    $this->sfont_style = $sfs;
	    $this->sfont_size = $sfz;	    
	} 
	else {
	    $sff = $this->sfont_family;
	    $sfs = $this->sfont_style;
	    $sfz = $this->sfont_size;	    
	}

	parent::Stroke($aImg,$ax,$ay);


	// For the builtin fonts we need to reduce the margins
	// since the bounding bx reported for the builtin fonts
	// are much larger than for the TTF fonts.
	if( $sff <= FF_FONT2 ) {
	    $sx -= 2;
	    $sy += 3;
	}

	$aImg->SetTextAlign('left','bottom');	
	$aImg->SetFont($sff,$sfs,$sfz);
	$aImg->PushColor($this->color);	
	$aImg->StrokeText($sx,$sy,$this->iSuper,$this->iSDir,'left');
	$aImg->PopColor();	
    }
}


//===================================================
// CLASS Grid
// Description: responsible for drawing grid lines in graph
//===================================================
class Grid {
    var $img;
    var $scale;
    var $grid_color='#DDDDDD',$grid_mincolor='#DDDDDD';
    var $type="solid";
    var $show=false, $showMinor=false,$weight=1;
    var $fill=false,$fillcolor=array('#EFEFEF','#BBCCFF');
//---------------
// CONSTRUCTOR
    function Grid(&$aAxis) {
	$this->scale = &$aAxis->scale;
	$this->img = &$aAxis->img;
    }
//---------------
// PUBLIC METHODS
    function SetColor($aMajColor,$aMinColor=false) {
	$this->grid_color=$aMajColor;
	if( $aMinColor === false ) 
	    $aMinColor = $aMajColor ;
	$this->grid_mincolor = $aMinColor;
    }
	
    function SetWeight($aWeight) {
	$this->weight=$aWeight;
    }
	
    // Specify if grid should be dashed, dotted or solid
    function SetLineStyle($aType) {
	$this->type = $aType;
    }
	
    // Decide if both major and minor grid should be displayed
    function Show($aShowMajor=true,$aShowMinor=false) {
	$this->show=$aShowMajor;
	$this->showMinor=$aShowMinor;
    }
    
    function SetFill($aFlg=true,$aColor1='lightgray',$aColor2='lightblue') {
	$this->fill = $aFlg;
	$this->fillcolor = array( $aColor1, $aColor2 );
    }
	
    // Display the grid
    function Stroke() {
	if( $this->showMinor ) {
	    $tmp = $this->grid_color;
	    $this->grid_color = $this->grid_mincolor;
	    $this->DoStroke($this->scale->ticks->ticks_pos);

	    $this->grid_color = $tmp;
	    $this->DoStroke($this->scale->ticks->maj_ticks_pos);
	}
	else {
	    $this->DoStroke($this->scale->ticks->maj_ticks_pos);
	}
    }
	
//--------------
// Private methods	
    // Draw the grid
    function DoStroke(&$aTicksPos) {
	if( !$this->show )
	    return;	
	$nbrgrids = count($aTicksPos);	

	if( $this->scale->type=="y" ) {
	    $xl=$this->img->left_margin;
	    $xr=$this->img->width-$this->img->right_margin;
	    
	    if( $this->fill ) {
		// Draw filled areas
		$y2 = $aTicksPos[0];
		$i=1;
		while( $i < $nbrgrids ) {
		    $y1 = $y2;
		    $y2 = $aTicksPos[$i++];
		    $this->img->SetColor($this->fillcolor[$i & 1]);
		    $this->img->FilledRectangle($xl,$y1,$xr,$y2);
		}
	    }

	    $this->img->SetColor($this->grid_color);
	    $this->img->SetLineWeight($this->weight);

	    // Draw grid lines
	    for($i=0; $i<$nbrgrids; ++$i) {
		$y=$aTicksPos[$i];
		if( $this->type == "solid" )
		    $this->img->Line($xl,$y,$xr,$y);
		elseif( $this->type == "dotted" )
		    $this->img->DashedLine($xl,$y,$xr,$y,1,6);
		elseif( $this->type == "dashed" )
		    $this->img->DashedLine($xl,$y,$xr,$y,2,4);
		elseif( $this->type == "longdashed" )
		    $this->img->DashedLine($xl,$y,$xr,$y,8,6);
	    }
	}
	elseif( $this->scale->type=="x" ) {	
	    $yu=$this->img->top_margin;
	    $yl=$this->img->height-$this->img->bottom_margin;
	    $limit=$this->img->width-$this->img->right_margin;

	    if( $this->fill ) {
		// Draw filled areas
		$x2 = $aTicksPos[0];
		$i=1;
		while( $i < $nbrgrids ) {
		    $x1 = $x2;
		    $x2 = min($aTicksPos[$i++],$limit) ;
		    $this->img->SetColor($this->fillcolor[$i & 1]);
		    $this->img->FilledRectangle($x1,$yu,$x2,$yl);
		}
	    }

	    $this->img->SetColor($this->grid_color);
	    $this->img->SetLineWeight($this->weight);

	    // We must also test for limit since we might have
	    // an offset and the number of ticks is calculated with
	    // assumption offset==0 so we might end up drawing one
	    // to many gridlines
	    $i=0;
	    $x=$aTicksPos[$i];	    
	    while( $i<count($aTicksPos) && ($x=$aTicksPos[$i]) <= $limit ) {
		if( $this->type == "solid" )				
		    $this->img->Line($x,$yl,$x,$yu);
		elseif( $this->type == "dotted" )
		    $this->img->DashedLine($x,$yl,$x,$yu,1,6);
		elseif( $this->type == "dashed" )
		    $this->img->DashedLine($x,$yl,$x,$yu,2,4);
		elseif( $this->type == "longdashed" )
		    $this->img->DashedLine($x,$yl,$x,$yu,8,6);	
		++$i;  
	    }
	}	
	else {
	    JpGraphError::RaiseL(25054,$this->scale->type);//('Internal error: Unknown grid axis ['.$this->scale->type.']');
	}
	return true;
    }
} // Class

//===================================================
// CLASS Axis
// Description: Defines X and Y axis. Notes that at the
// moment the code is not really good since the axis on
// several occasion must know wheter it's an X or Y axis.
// This was a design decision to make the code easier to
// follow. 
//===================================================
class Axis {
    var $pos = false;
    var $weight=1;
    var $color=array(0,0,0),$label_color=array(0,0,0);
    var $img=null,$scale=null; 
    var $hide=false;
    var $ticks_label=false, $ticks_label_colors=null;
    var $show_first_label=true,$show_last_label=true;
    var $label_step=1; // Used by a text axis to specify what multiple of major steps
    // should be labeled.
    var $tick_step=1;
    var $labelPos=0;   // Which side of the axis should the labels be?
    var $title=null,$title_adjust,$title_margin,$title_side=SIDE_LEFT;
    var $font_family=FF_FONT1,$font_style=FS_NORMAL,$font_size=12,$label_angle=0;
    var $tick_label_margin=5;
    var $label_halign = '',$label_valign = '', $label_para_align='left';
    var $hide_line=false,$hide_labels=false;
    var $iDeltaAbsPos=0;
    //var $hide_zero_label=false;

//---------------
// CONSTRUCTOR
    function Axis(&$img,&$aScale,$color=array(0,0,0)) {
	$this->img = &$img;
	$this->scale = &$aScale;
	$this->color = $color;
	$this->title=new Text("");
		
	if( $aScale->type=="y" ) {
	    $this->title_margin = 25;
	    $this->title_adjust="middle";
	    $this->title->SetOrientation(90);
	    $this->tick_label_margin=7;
	    $this->labelPos=SIDE_LEFT;
	    //$this->SetLabelFormat('%.1f');
	}
	else {
	    $this->title_margin = 5;
	    $this->title_adjust="high";
	    $this->title->SetOrientation(0);			
	    $this->tick_label_margin=5;
	    $this->labelPos=SIDE_DOWN;
	    $this->title_side=SIDE_DOWN;
	    //$this->SetLabelFormat('%.0f');
	}
    }
//---------------
// PUBLIC METHODS	
	
    function SetLabelFormat($aFormStr) {
	$this->scale->ticks->SetLabelFormat($aFormStr);
    }
	
    function SetLabelFormatString($aFormStr,$aDate=false) {
	$this->scale->ticks->SetLabelFormat($aFormStr,$aDate);
    }
	
    function SetLabelFormatCallback($aFuncName) {
	$this->scale->ticks->SetFormatCallback($aFuncName);
    }

    function SetLabelAlign($aHAlign,$aVAlign="top",$aParagraphAlign='left') {
	$this->label_halign = $aHAlign;
	$this->label_valign = $aVAlign;
	$this->label_para_align = $aParagraphAlign;
    }		

    // Don't display the first label
    function HideFirstTickLabel($aShow=false) {
	$this->show_first_label=$aShow;
    }

    function HideLastTickLabel($aShow=false) {
	$this->show_last_label=$aShow;
    }

    // Manually specify the major and (optional) minor tick position and labels
    function SetTickPositions($aMajPos,$aMinPos=NULL,$aLabels=NULL) {
	$this->scale->ticks->SetTickPositions($aMajPos,$aMinPos,$aLabels);
    }

    // Manually specify major tick positions and optional labels
    function SetMajTickPositions($aMajPos,$aLabels=NULL) {
	$this->scale->ticks->SetTickPositions($aMajPos,NULL,$aLabels);
    }

    // Hide minor or major tick marks
    function HideTicks($aHideMinor=true,$aHideMajor=true) {
	$this->scale->ticks->SupressMinorTickMarks($aHideMinor);
	$this->scale->ticks->SupressTickMarks($aHideMajor);
    }

    // Hide zero label
    function HideZeroLabel($aFlag=true) {
	$this->scale->ticks->SupressZeroLabel();
	//$this->hide_zero_label = $aFlag;
    }
	
    function HideFirstLastLabel() {
	// The two first calls to ticks method will supress 
	// automatically generated scale values. However, that
	// will not affect manually specified value, e.g text-scales.
	// therefor we also make a kludge here to supress manually
	// specified scale labels.
	$this->scale->ticks->SupressLast();
	$this->scale->ticks->SupressFirst();
	$this->show_first_label	= false;
	$this->show_last_label = false;
    }
	
    // Hide the axis
    function Hide($aHide=true) {
	$this->hide=$aHide;
    }

    // Hide the actual axis-line, but still print the labels
    function HideLine($aHide=true) {
	$this->hide_line = $aHide;
    }

    function HideLabels($aHide=true) {
	$this->hide_labels = $aHide;
    }
    

    // Weight of axis
    function SetWeight($aWeight) {
	$this->weight = $aWeight;
    }

    // Axis color
    function SetColor($aColor,$aLabelColor=false) {
	$this->color = $aColor;
	if( !$aLabelColor ) $this->label_color = $aColor;
	else $this->label_color = $aLabelColor;
    }
	
    // Title on axis
    function SetTitle($aTitle,$aAdjustAlign="high") {
	$this->title->Set($aTitle);
	$this->title_adjust=$aAdjustAlign;
    }
	
    // Specify distance from the axis
    function SetTitleMargin($aMargin) {
	$this->title_margin=$aMargin;
    }
	
    // Which side of the axis should the axis title be?
    function SetTitleSide($aSideOfAxis) {
	$this->title_side = $aSideOfAxis;
    }

    // Utility function to set the direction for tick marks
    function SetTickDirection($aDir) {
    	// Will be deprecated from 1.7    	
    	if( ERR_DEPRECATED )
	    JpGraphError::RaiseL(25055);//('Axis::SetTickDirection() is deprecated. Use Axis::SetTickSide() instead');
	$this->scale->ticks->SetSide($aDir);
    }
    
    function SetTickSide($aDir) {
	$this->scale->ticks->SetSide($aDir);
    }
	
    // Specify text labels for the ticks. One label for each data point
    function SetTickLabels($aLabelArray,$aLabelColorArray=null) {
	$this->ticks_label = $aLabelArray;
	$this->ticks_label_colors = $aLabelColorArray;
    }
	
    // How far from the axis should the labels be drawn
    function SetTickLabelMargin($aMargin) {
	if( ERR_DEPRECATED )    	
	    JpGraphError::RaiseL(25056);//('SetTickLabelMargin() is deprecated. Use Axis::SetLabelMargin() instead.');
      	$this->tick_label_margin=$aMargin;
    }

    function SetLabelMargin($aMargin) {
	$this->tick_label_margin=$aMargin;
    }
	
    // Specify that every $step of the ticks should be displayed starting
    // at $start
    // DEPRECATED FUNCTION: USE SetTextTickInterval() INSTEAD
    function SetTextTicks($step,$start=0) {
	JpGraphError::RaiseL(25057);//(" SetTextTicks() is deprecated. Use SetTextTickInterval() instead.");		
    }

    // Specify that every $step of the ticks should be displayed starting
    // at $start	
    function SetTextTickInterval($aStep,$aStart=0) {
	$this->scale->ticks->SetTextLabelStart($aStart);
	$this->tick_step=$aStep;
    }
	 
    // Specify that every $step tick mark should have a label 
    // should be displayed starting
    function SetTextLabelInterval($aStep,$aStart=0) {
	if( $aStep < 1 )
	    JpGraphError::RaiseL(25058);//(" Text label interval must be specified >= 1.");
	$this->scale->ticks->SetTextLabelStart($aStart);
	$this->label_step=$aStep;
    }
	
    // Which side of the axis should the labels be on?
    function SetLabelPos($aSidePos) {
    	// This will be deprecated from 1.7
	if( ERR_DEPRECATED )    	
	    JpGraphError::RaiseL(25059);//('SetLabelPos() is deprecated. Use Axis::SetLabelSide() instead.');
	$this->labelPos=$aSidePos;
    }
    
    function SetLabelSide($aSidePos) {
	$this->labelPos=$aSidePos;
    }

    // Set the font
    function SetFont($aFamily,$aStyle=FS_NORMAL,$aSize=10) {
	$this->font_family = $aFamily;
	$this->font_style = $aStyle;
	$this->font_size = $aSize;
    }

    // Position for axis line on the "other" scale
    function SetPos($aPosOnOtherScale) {
	$this->pos=$aPosOnOtherScale;
    }

    // Set the position of the axis to be X-pixels delta to the right 
    // of the max X-position (used to position the multiple Y-axis)
    function SetPosAbsDelta($aDelta) {
      $this->iDeltaAbsPos=$aDelta;
    }
	
    // Specify the angle for the tick labels
    function SetLabelAngle($aAngle) {
	$this->label_angle = $aAngle;
    }	
	
    // Stroke the axis.
    function Stroke($aOtherAxisScale,$aStrokeLabels=true) {		
	if( $this->hide ) return;		
	if( is_numeric($this->pos) ) {
	    $pos=$aOtherAxisScale->Translate($this->pos);
	}
	else {	// Default to minimum of other scale if pos not set		
	    if( ($aOtherAxisScale->GetMinVal() >= 0 && $this->pos==false) || $this->pos=="min" ) {
		$pos = $aOtherAxisScale->scale_abs[0];
	    }
	    elseif($this->pos == "max") {
		$pos = $aOtherAxisScale->scale_abs[1];
	    }
	    else { // If negative set x-axis at 0
		$this->pos=0;
		$pos=$aOtherAxisScale->Translate(0);
	    }
	}	
	$pos += $this->iDeltaAbsPos;
	$this->img->SetLineWeight($this->weight);
	$this->img->SetColor($this->color);		
	$this->img->SetFont($this->font_family,$this->font_style,$this->font_size);
	if( $this->scale->type == "x" ) {
	    if( !$this->hide_line ) 
		$this->img->FilledRectangle($this->img->left_margin,$pos,
					    $this->img->width-$this->img->right_margin,$pos+$this->weight-1);
	    if( $this->title_side == SIDE_DOWN ) {
		$y = $pos + $this->img->GetFontHeight() + $this->title_margin + $this->title->margin;
		$yalign = 'top';
	    }
	    else {
		$y = $pos - $this->img->GetFontHeight() - $this->title_margin - $this->title->margin;
		$yalign = 'bottom';
	    }

	    if( $this->title_adjust=="high" )
		$this->title->Pos($this->img->width-$this->img->right_margin,$y,"right",$yalign);
	    elseif( $this->title_adjust=="middle" || $this->title_adjust=="center" ) 
		$this->title->Pos(($this->img->width-$this->img->left_margin-$this->img->right_margin)/2+$this->img->left_margin,$y,"center",$yalign);
	    elseif($this->title_adjust=="low")
		$this->title->Pos($this->img->left_margin,$y,"left",$yalign);
	    else {	
		JpGraphError::RaiseL(25060,$this->title_adjust);//('Unknown alignment specified for X-axis title. ('.$this->title_adjust.')');
	    }
	}
	elseif( $this->scale->type == "y" ) {
	    // Add line weight to the height of the axis since
	    // the x-axis could have a width>1 and we want the axis to fit nicely together.
	    if( !$this->hide_line ) 
		$this->img->FilledRectangle($pos-$this->weight+1,$this->img->top_margin,
					    $pos,$this->img->height-$this->img->bottom_margin+$this->weight-1);
	    $x=$pos ;
	    if( $this->title_side == SIDE_LEFT ) {
		$x -= $this->title_margin;
		$x -= $this->title->margin;
		$halign="right";
	    }
	    else {
		$x += $this->title_margin;
		$x += $this->title->margin;
		$halign="left";
	    }
	    // If the user has manually specified an hor. align
	    // then we override the automatic settings with this
	    // specifed setting. Since default is 'left' we compare
	    // with that. (This means a manually set 'left' align
	    // will have no effect.)
	    if( $this->title->halign != 'left' ) 
		$halign = $this->title->halign;
	    if( $this->title_adjust=="high" ) 
		$this->title->Pos($x,$this->img->top_margin,$halign,"top"); 
	    elseif($this->title_adjust=="middle" || $this->title_adjust=="center")  
		$this->title->Pos($x,($this->img->height-$this->img->top_margin-$this->img->bottom_margin)/2+$this->img->top_margin,$halign,"center");
	    elseif($this->title_adjust=="low")
		$this->title->Pos($x,$this->img->height-$this->img->bottom_margin,$halign,"bottom");
	    else	
		JpGraphError::RaiseL(25061,$this->title_adjust);//('Unknown alignment specified for Y-axis title. ('.$this->title_adjust.')');
		
	}
	$this->scale->ticks->Stroke($this->img,$this->scale,$pos);
	if( $aStrokeLabels ) {
	    if( !$this->hide_labels )
		$this->StrokeLabels($pos);
	    $this->title->Stroke($this->img);
	}
    }

//---------------
// PRIVATE METHODS	
    // Draw all the tick labels on major tick marks
    function StrokeLabels($aPos,$aMinor=false,$aAbsLabel=false) {

	$this->img->SetColor($this->label_color);
	$this->img->SetFont($this->font_family,$this->font_style,$this->font_size);
	$yoff=$this->img->GetFontHeight()/2;

	// Only draw labels at major tick marks
	$nbr = count($this->scale->ticks->maj_ticks_label);

	// We have the option to not-display the very first mark
	// (Usefull when the first label might interfere with another
	// axis.)
	$i = $this->show_first_label ? 0 : 1 ;
	if( !$this->show_last_label ) --$nbr;
	// Now run through all labels making sure we don't overshoot the end
	// of the scale.	
	$ncolor=0;
	if( isset($this->ticks_label_colors) )
	    $ncolor=count($this->ticks_label_colors);
	
	while( $i<$nbr ) {
	    // $tpos holds the absolute text position for the label
	    $tpos=$this->scale->ticks->maj_ticklabels_pos[$i];

	    // Note. the $limit is only used for the x axis since we
	    // might otherwise overshoot if the scale has been centered
	    // This is due to us "loosing" the last tick mark if we center.
	    if( $this->scale->type=="x" && $tpos > $this->img->width-$this->img->right_margin+1 ) {
	    	return; 
	    }
	    // we only draw every $label_step label
	    if( ($i % $this->label_step)==0 ) {

		// Set specific label color if specified
		if( $ncolor > 0 )
		    $this->img->SetColor($this->ticks_label_colors[$i % $ncolor]);
		
		// If the label has been specified use that and in other case
		// just label the mark with the actual scale value 
		$m=$this->scale->ticks->GetMajor();
				
		// ticks_label has an entry for each data point and is the array
		// that holds the labels set by the user. If the user hasn't 
		// specified any values we use whats in the automatically asigned
		// labels in the maj_ticks_label
		if( isset($this->ticks_label[$i*$m]) )
		    $label=$this->ticks_label[$i*$m];
		else {
		    if( $aAbsLabel ) 
			$label=abs($this->scale->ticks->maj_ticks_label[$i]);
		    else
			$label=$this->scale->ticks->maj_ticks_label[$i];
		    if( $this->scale->textscale && $this->scale->ticks->label_formfunc == '' ) {
			++$label;
		    }
		}
					
		//if( $this->hide_zero_label && $label==0.0 ) {
		//	++$i;
		//	continue;
		//}					
					
		if( $this->scale->type == "x" ) {
		    if( $this->labelPos == SIDE_DOWN ) {
			if( $this->label_angle==0 || $this->label_angle==90 ) {
			    if( $this->label_halign=='' && $this->label_valign=='')
				$this->img->SetTextAlign('center','top');
			    else
			    	$this->img->SetTextAlign($this->label_halign,$this->label_valign);
			    
			}
			else {
			    if( $this->label_halign=='' && $this->label_valign=='')
				$this->img->SetTextAlign("right","top");
			    else
				$this->img->SetTextAlign($this->label_halign,$this->label_valign);
			}

			$this->img->StrokeText($tpos,$aPos+$this->tick_label_margin,$label,
					       $this->label_angle,$this->label_para_align);
		    }
		    else {
			if( $this->label_angle==0 || $this->label_angle==90 ) {
			    if( $this->label_halign=='' && $this->label_valign=='')
				$this->img->SetTextAlign("center","bottom");
			    else
			    	$this->img->SetTextAlign($this->label_halign,$this->label_valign);
			}
			else {
			    if( $this->label_halign=='' && $this->label_valign=='')
				$this->img->SetTextAlign("right","bottom");
			    else
			    	$this->img->SetTextAlign($this->label_halign,$this->label_valign);
			}
			$this->img->StrokeText($tpos,$aPos-$this->tick_label_margin,$label,
					       $this->label_angle,$this->label_para_align);
		    }
		}
		else {
		    // scale->type == "y"
		    //if( $this->label_angle!=0 ) 
		    //JpGraphError::Raise(" Labels at an angle are not supported on Y-axis");
		    if( $this->labelPos == SIDE_LEFT ) { // To the left of y-axis					
			if( $this->label_halign=='' && $this->label_valign=='')	
			    $this->img->SetTextAlign("right","center");
			else
			    $this->img->SetTextAlign($this->label_halign,$this->label_valign);
			$this->img->StrokeText($aPos-$this->tick_label_margin,$tpos,$label,$this->label_angle,$this->label_para_align);	
		    }
		    else { // To the right of the y-axis
			if( $this->label_halign=='' && $this->label_valign=='')	
			    $this->img->SetTextAlign("left","center");
			else
			    $this->img->SetTextAlign($this->label_halign,$this->label_valign);
			$this->img->StrokeText($aPos+$this->tick_label_margin,$tpos,$label,$this->label_angle,$this->label_para_align);	
		    }
		}
	    }
	    ++$i;	
	}								
    }			

} // Class

//===================================================
// CLASS Ticks
// Description: Abstract base class for drawing linear and logarithmic
// tick marks on axis
//===================================================
class Ticks {
    var $minor_abs_size=3, $major_abs_size=5;
    var $direction=1; // Should ticks be in(=1) the plot area or outside (=-1)?
    var $scale;
    var $is_set=false;
    var $precision;
    var $supress_zerolabel=false,$supress_first=false;
    var $supress_last=false,$supress_tickmarks=false,$supress_minor_tickmarks=false;
    var $mincolor="",$majcolor="";
    var $weight=1;
    var $label_formatstr='';   // C-style format string to use for labels
    var $label_formfunc='';
    var $label_dateformatstr='';
    var $label_usedateformat=FALSE;


//---------------
// CONSTRUCTOR
    function Ticks(&$aScale) {
	$this->scale=&$aScale;
	$this->precision = -1;
    }

//---------------
// PUBLIC METHODS	
    // Set format string for automatic labels
    function SetLabelFormat($aFormatString,$aDate=FALSE) {
	$this->label_formatstr=$aFormatString;
	$this->label_usedateformat=$aDate;
    }

    function SetLabelDateFormat($aFormatString) {
	$this->label_dateformatstr=$aFormatString;
    }
	
    function SetFormatCallback($aCallbackFuncName) {
	$this->label_formfunc = $aCallbackFuncName;
    }
	
    // Don't display the first zero label
    function SupressZeroLabel($aFlag=true) {
	$this->supress_zerolabel=$aFlag;
    }
	
    // Don't display minor tick marks
    function SupressMinorTickMarks($aHide=true) {
	$this->supress_minor_tickmarks=$aHide;
    }
	
    // Don't display major tick marks
    function SupressTickMarks($aHide=true) {
	$this->supress_tickmarks=$aHide;
    }
	
    // Hide the first tick mark
    function SupressFirst($aHide=true) {
	$this->supress_first=$aHide;
    }
	
    // Hide the last tick mark
    function SupressLast($aHide=true) {
	$this->supress_last=$aHide;
    }

    // Size (in pixels) of minor tick marks
    function GetMinTickAbsSize() {
	return $this->minor_abs_size;
    }
	
    // Size (in pixels) of major tick marks
    function GetMajTickAbsSize() {
	return $this->major_abs_size;		
    }
	
    function SetSize($aMajSize,$aMinSize=3) {
	$this->major_abs_size = $aMajSize;		
	$this->minor_abs_size = $aMinSize;		
    }

    // Have the ticks been specified
    function IsSpecified() {
	return $this->is_set;
    }
	
    // Set the distance between major and minor tick marks
    function Set($aMaj,$aMin) {
	// "Virtual method"
	// Should be implemented by the concrete subclass
	// if any action is wanted.
    }
	
    // Specify number of decimals in automatic labels
    // Deprecated from 1.4. Use SetFormatString() instead
    function SetPrecision($aPrecision) { 	
    	if( ERR_DEPRECATED )
	    JpGraphError::RaiseL(25063);//('Ticks::SetPrecision() is deprecated. Use Ticks::SetLabelFormat() (or Ticks::SetFormatCallback()) instead');
	$this->precision=$aPrecision;
    }

    function SetSide($aSide) {
	$this->direction=$aSide;
    }
	
    // Which side of the axis should the ticks be on
    function SetDirection($aSide=SIDE_RIGHT) {
	$this->direction=$aSide;
    }
	
    // Set colors for major and minor tick marks
    function SetMarkColor($aMajorColor,$aMinorColor="") {
	$this->SetColor($aMajorColor,$aMinorColor);
    }
    
    function SetColor($aMajorColor,$aMinorColor="") {
	$this->majcolor=$aMajorColor;
		
	// If not specified use same as major
	if( $aMinorColor=="" ) 
	    $this->mincolor=$aMajorColor;
	else
	    $this->mincolor=$aMinorColor;
    }
	
    function SetWeight($aWeight) {
	$this->weight=$aWeight;
    }
	
} // Class

//===================================================
// CLASS LinearTicks
// Description: Draw linear ticks on axis
//===================================================
class LinearTicks extends Ticks {
    var $minor_step=1, $major_step=2;
    var $xlabel_offset=0,$xtick_offset=0;
    var $label_offset=0; // What offset should the displayed label have
    // i.e should we display 0,1,2 or 1,2,3,4 or 2,3,4 etc
    var $text_label_start=0;
    var $iManualTickPos = NULL, $iManualMinTickPos = NULL, $iManualTickLabels = NULL;
    var $maj_ticks_pos = array(), $maj_ticklabels_pos = array(), 
	$ticks_pos = array(), $maj_ticks_label = array();

//---------------
// CONSTRUCTOR
    function LinearTicks() {
	$this->precision = -1;
    }

//---------------
// PUBLIC METHODS	
	
	
    // Return major step size in world coordinates
    function GetMajor() {
	return $this->major_step;
    }
	
    // Return minor step size in world coordinates
    function GetMinor() {
	return $this->minor_step;
    }
	
    // Set Minor and Major ticks (in world coordinates)
    function Set($aMajStep,$aMinStep=false) {
	if( $aMinStep==false ) 
	    $aMinStep=$aMajStep;
    	
	if( $aMajStep <= 0 || $aMinStep <= 0 ) {
	    JpGraphError::RaiseL(25064);
//(" Minor or major step size is 0. Check that you haven't got an accidental SetTextTicks(0) in your code. If this is not the case you might have stumbled upon a bug in JpGraph. Please report this and if possible include the data that caused the problem.");
	}
		
	$this->major_step=$aMajStep;
	$this->minor_step=$aMinStep;
	$this->is_set = true;
    }

    function SetMajTickPositions($aMajPos,$aLabels=NULL) {
	$this->SetTickPositions($aMajPos,NULL,$aLabels);
    }

    function SetTickPositions($aMajPos,$aMinPos=NULL,$aLabels=NULL) {
	if( !is_array($aMajPos) || ($aMinPos!==NULL && !is_array($aMinPos)) ) {
	    JpGraphError::RaiseL(25065);//('Tick positions must be specifued as an array()');
	    return;
	}
	$n=count($aMajPos);
	if( is_array($aLabels) && (count($aLabels) != $n) ) {
	    JpGraphError::RaiseL(25066);//('When manually specifying tick positions and labels the number of labels must be the same as the number of specified ticks.');
	    return;
	}
	$this->iManualTickPos = $aMajPos;
	$this->iManualMinTickPos = $aMinPos;
	$this->iManualTickLabels = $aLabels;
    }

    // Specify all the tick positions manually and possible also the exact labels 
    function _doManualTickPos($aScale) { 
	$n=count($this->iManualTickPos);
	$m=count($this->iManualMinTickPos);
	$doLbl=count($this->iManualTickLabels) > 0;
	$this->use_manualtickpos=true;

	$this->maj_ticks_pos = array();
	$this->maj_ticklabels_pos = array();
	$this->ticks_pos = array();

	// Now loop through the supplied positions and translate them to screen coordinates
	// and store them in the maj_label_positions
	$minScale = $aScale->scale[0];
	$maxScale = $aScale->scale[1];
	$j=0;
	for($i=0; $i < $n ; ++$i ) {
	    // First make sure that the first tick is not lower than the lower scale value
	    if( !isset($this->iManualTickPos[$i])  || 
		$this->iManualTickPos[$i] < $minScale  || $this->iManualTickPos[$i] > $maxScale) {
		continue;
	    }


	    $this->maj_ticks_pos[$j] = $aScale->Translate($this->iManualTickPos[$i]);
	    $this->maj_ticklabels_pos[$j] = $this->maj_ticks_pos[$j];	

	    // Set the minor tick marks the same as major if not specified
	    if( $m <= 0 ) {
		$this->ticks_pos[$j] = $this->maj_ticks_pos[$j];
	    }

	    if( $doLbl ) { 
		$this->maj_ticks_label[$j] = $this->iManualTickLabels[$i];
	    }
	    else {
		$this->maj_ticks_label[$j]=$this->_doLabelFormat($this->iManualTickPos[$i],$i,$n);
	    }
	    ++$j;
	}

	// Some sanity check
	if( count($this->maj_ticks_pos) < 2 ) {
	    JpGraphError::RaiseL(25067);//('Your manually specified scale and ticks is not correct. The scale seems to be too small to hold any of the specified tickl marks.');
	}

	// Setup the minor tick marks
	$j=0;
	for($i=0; $i < $m; ++$i ) {
	    if(  empty($this->iManualMinTickPos[$i]) || 
		 $this->iManualMinTickPos[$i] < $minScale  || $this->iManualMinTickPos[$i] > $maxScale) 
		continue;
	    $this->ticks_pos[$j] = $aScale->Translate($this->iManualMinTickPos[$i]);
	    ++$j;
	}
    }

    function _doAutoTickPos($aScale) {
	$maj_step_abs = $aScale->scale_factor*$this->major_step;		
	$min_step_abs = $aScale->scale_factor*$this->minor_step;		

	if( $min_step_abs==0 || $maj_step_abs==0 ) {
	    JpGraphError::RaiseL(25068);//("A plot has an illegal scale. This could for example be that you are trying to use text autoscaling to draw a line plot with only one point or that the plot area is too small. It could also be that no input data value is numeric (perhaps only '-' or 'x')");
	}
	// We need to make this an int since comparing it below
	// with the result from round() can give wrong result, such that
	// (40 < 40) == TRUE !!!
	$limit = (int)$aScale->scale_abs[1];	

	if( $aScale->textscale ) {
	    // This can only be true for a X-scale (horizontal)
	    // Define ticks for a text scale. This is slightly different from a 
	    // normal linear type of scale since the position might be adjusted
	    // and the labels start at on
	    $label = (float)$aScale->GetMinVal()+$this->text_label_start+$this->label_offset;	
	    $start_abs=$aScale->scale_factor*$this->text_label_start;
	    $nbrmajticks=ceil(($aScale->GetMaxVal()-$aScale->GetMinVal()-$this->text_label_start )/$this->major_step)+1;	
	    $x = $aScale->scale_abs[0]+$start_abs+$this->xlabel_offset*$min_step_abs;	
	    for( $i=0; $label <= $aScale->GetMaxVal()+$this->label_offset; ++$i ) {
		// Apply format to label
		$this->maj_ticks_label[$i]=$this->_doLabelFormat($label,$i,$nbrmajticks);
		$label+=$this->major_step;

		// The x-position of the tick marks can be different from the labels.
		// Note that we record the tick position (not the label) so that the grid
		// happen upon tick marks and not labels.
		$xtick=$aScale->scale_abs[0]+$start_abs+$this->xtick_offset*$min_step_abs+$i*$maj_step_abs;
		$this->maj_ticks_pos[$i]=$xtick;
		$this->maj_ticklabels_pos[$i] = round($x);				
		$x += $maj_step_abs;
	    }
	}
	else {
	    $label = $aScale->GetMinVal();	
	    $abs_pos = $aScale->scale_abs[0];
	    $j=0; $i=0;
	    $step = round($maj_step_abs/$min_step_abs);
	    if( $aScale->type == "x" ) {
		// For a normal linear type of scale the major ticks will always be multiples
		// of the minor ticks. In order to avoid any rounding issues the major ticks are
		// defined as every "step" minor ticks and not calculated separately
		$nbrmajticks=ceil(($aScale->GetMaxVal()-$aScale->GetMinVal()-$this->text_label_start )/$this->major_step)+1; 
		while( round($abs_pos) <= $limit ) {
		    $this->ticks_pos[] = round($abs_pos);
		    $this->ticks_label[] = $label;
		    if( $i % $step == 0 && $j < $nbrmajticks ) {
			$this->maj_ticks_pos[$j] = round($abs_pos);
			$this->maj_ticklabels_pos[$j] = round($abs_pos);
			$this->maj_ticks_label[$j]=$this->_doLabelFormat($label,$j,$nbrmajticks);
			++$j;
		    }
		    ++$i;
		    $abs_pos += $min_step_abs;
		    $label+=$this->minor_step;
		}
	    }
	    elseif( $aScale->type == "y" ) {
		$nbrmajticks=floor(($aScale->GetMaxVal()-$aScale->GetMinVal())/$this->major_step)+1;
		while( round($abs_pos) >= $limit ) {
		    $this->ticks_pos[$i] = round($abs_pos); 
		    $this->ticks_label[$i]=$label;
		    if( $i % $step == 0 && $j < $nbrmajticks) {
			$this->maj_ticks_pos[$j] = round($abs_pos);
			$this->maj_ticklabels_pos[$j] = round($abs_pos);
			$this->maj_ticks_label[$j]=$this->_doLabelFormat($label,$j,$nbrmajticks);
			++$j;
		    }
		    ++$i;
		    $abs_pos += $min_step_abs;
		    $label += $this->minor_step;
		}	
	    }
	}	
    }

    function _doLabelFormat($aVal,$aIdx,$aNbrTicks) {

	// If precision hasn't been specified set it to a sensible value
	if( $this->precision==-1 ) { 
	    $t = log10($this->minor_step);
	    if( $t > 0 )
		$precision = 0;
	    else
		$precision = -floor($t);
	}
	else
	    $precision = $this->precision;

	if( $this->label_formfunc != '' ) {
	    $f=$this->label_formfunc;
	    $l = call_user_func($f,$aVal);
	}	
	elseif( $this->label_formatstr != '' || $this->label_dateformatstr != '' ) {
	    if( $this->label_usedateformat ) {
		$l = date($this->label_formatstr,$aVal);
	    }
	    else {
		if( $this->label_dateformatstr !== '' )
		    $l = date($this->label_dateformatstr,$aVal);
		else
		    $l = sprintf($this->label_formatstr,$aVal);
	    }
	}
	else {
	    $l = sprintf('%01.'.$precision.'f',round($aVal,$precision));
	}
	
	if( ($this->supress_zerolabel && $l==0) ||  ($this->supress_first && $aIdx==0) ||
	    ($this->supress_last  && $aIdx==$aNbrTicks-1) ) {
	    $l='';
	}
	return $l;
    }

    // Stroke ticks on either X or Y axis
    function _StrokeTicks(&$aImg,$aScale,$aPos) {
	$hor = $aScale->type == 'x';
	$aImg->SetLineWeight($this->weight);	

	// We need to make this an int since comparing it below
	// with the result from round() can give wrong result, such that
	// (40 < 40) == TRUE !!!
	$limit = (int)$aScale->scale_abs[1];
		
	// A text scale doesn't have any minor ticks
	if( !$aScale->textscale ) {
	    // Stroke minor ticks
	    $yu = $aPos - $this->direction*$this->GetMinTickAbsSize();
	    $xr = $aPos + $this->direction*$this->GetMinTickAbsSize();
	    $n = count($this->ticks_pos);
	    for($i=0; $i < $n; ++$i ) {
		if( !$this->supress_tickmarks && !$this->supress_minor_tickmarks) {
		    if( $this->mincolor!="" ) $aImg->PushColor($this->mincolor);
		    if( $hor ) {
			//if( $this->ticks_pos[$i] <= $limit ) 
			$aImg->Line($this->ticks_pos[$i],$aPos,$this->ticks_pos[$i],$yu); 
		    }
		    else {
			//if( $this->ticks_pos[$i] >= $limit ) 
			$aImg->Line($aPos,$this->ticks_pos[$i],$xr,$this->ticks_pos[$i]); 
		    }
		    if( $this->mincolor!="" ) $aImg->PopColor();
		}
	    }
	}

	// Stroke major ticks
	$yu = $aPos - $this->direction*$this->GetMajTickAbsSize();
	$xr = $aPos + $this->direction*$this->GetMajTickAbsSize();
	$nbrmajticks=ceil(($aScale->GetMaxVal()-$aScale->GetMinVal()-$this->text_label_start )/$this->major_step)+1;
	$n = count($this->maj_ticks_pos);
	for($i=0; $i < $n ; ++$i ) {
	    if(!($this->xtick_offset > 0 && $i==$nbrmajticks-1) && !$this->supress_tickmarks) {
		if( $this->majcolor!="" ) $aImg->PushColor($this->majcolor);
		if( $hor ) {
		    //if( $this->maj_ticks_pos[$i] <= $limit ) 
		    $aImg->Line($this->maj_ticks_pos[$i],$aPos,$this->maj_ticks_pos[$i],$yu); 
		}
		else {
		    //if( $this->maj_ticks_pos[$i] >= $limit ) 
		    $aImg->Line($aPos,$this->maj_ticks_pos[$i],$xr,$this->maj_ticks_pos[$i]); 
		}
		if( $this->majcolor!="" ) $aImg->PopColor();
	    }
	}
	
    }

    // Draw linear ticks
    function Stroke(&$aImg,$aScale,$aPos) {
	if( $this->iManualTickPos != NULL ) 
	    $this->_doManualTickPos($aScale);
	else 
	    $this->_doAutoTickPos($aScale);
	$this->_StrokeTicks($aImg,$aScale,$aPos, $aScale->type == 'x' );
    }

//---------------
// PRIVATE METHODS
    // Spoecify the offset of the displayed tick mark with the tick "space"
    // Legal values for $o is [0,1] used to adjust where the tick marks and label 
    // should be positioned within the major tick-size
    // $lo specifies the label offset and $to specifies the tick offset
    // this comes in handy for example in bar graphs where we wont no offset for the
    // tick but have the labels displayed halfway under the bars.
    function SetXLabelOffset($aLabelOff,$aTickOff=-1) {
	$this->xlabel_offset=$aLabelOff;
	if( $aTickOff==-1 )	// Same as label offset
	    $this->xtick_offset=$aLabelOff;
	else
	    $this->xtick_offset=$aTickOff;
	if( $aLabelOff>0 )
	    $this->SupressLast();	// The last tick wont fit
    }

    // Which tick label should we start with?
    function SetTextLabelStart($aTextLabelOff) {
	$this->text_label_start=$aTextLabelOff;
    }
	
} // Class

//===================================================
// CLASS LinearScale
// Description: Handle linear scaling between screen and world 
//===================================================
class LinearScale {
    var $scale=array(0,0);
    var $scale_abs=array(0,0);
    var $scale_factor; // Scale factor between world and screen
    var $world_size;	// Plot area size in world coordinates
    var $world_abs_size; // Plot area size in pixels
    var $off; // Offset between image edge and plot area
    var $type; // is this x or y scale ?
    var $ticks=null; // Store ticks
    var $text_scale_off = 0;
    var $autoscale_min=false; // Forced minimum value, auto determine max
    var $autoscale_max=false; // Forced maximum value, auto determine min
    var $gracetop=0,$gracebottom=0;
    var $intscale=false; // Restrict autoscale to integers
    var $textscale=false; // Just a flag to let the Plot class find out if
    // we are a textscale or not. This is a cludge since
    // this ionformatyion is availabale in Graph::axtype but
    // we don't have access to the graph object in the Plots
    // stroke method. So we let graph store the status here
    // when the linear scale is created. A real cludge...
    var $auto_ticks=false; // When using manual scale should the ticks be automatically set?
    var $name = 'lin';
//---------------
// CONSTRUCTOR
    function LinearScale($aMin=0,$aMax=0,$aType="y") {
	assert($aType=="x" || $aType=="y" );
	assert($aMin<=$aMax);
		
	$this->type=$aType;
	$this->scale=array($aMin,$aMax);		
	$this->world_size=$aMax-$aMin;	
	$this->ticks = new LinearTicks();
    }

//---------------
// PUBLIC METHODS	
    // Check if scale is set or if we should autoscale
    // We should do this is either scale or ticks has not been set
    function IsSpecified() {
	if( $this->GetMinVal()==$this->GetMaxVal() ) {		// Scale not set
	    return false;
	}
	return true;
    }
	
    // Set the minimum data value when the autoscaling is used. 
    // Usefull if you want a fix minimum (like 0) but have an
    // automatic maximum
    function SetAutoMin($aMin) {
	$this->autoscale_min=$aMin;
    }

    // Set the minimum data value when the autoscaling is used. 
    // Usefull if you want a fix minimum (like 0) but have an
    // automatic maximum
    function SetAutoMax($aMax) {
	$this->autoscale_max=$aMax;
    }

    // If the user manually specifies a scale should the ticks
    // still be set automatically?
    function SetAutoTicks($aFlag=true) {
	$this->auto_ticks = $aFlag;
    }

    // Specify scale "grace" value (top and bottom)
    function SetGrace($aGraceTop,$aGraceBottom=0) {
	if( $aGraceTop<0 || $aGraceBottom < 0  )
	    JpGraphError::RaiseL(25069);//(" Grace must be larger then 0");
	$this->gracetop=$aGraceTop;
	$this->gracebottom=$aGraceBottom;
    }
	
    // Get the minimum value in the scale
    function GetMinVal() {
	return $this->scale[0];
    }
	
    // get maximum value for scale
    function GetMaxVal() {
	return $this->scale[1];
    }
		
    // Specify a new min/max value for sclae	
    function Update(&$aImg,$aMin,$aMax) {
	$this->scale=array($aMin,$aMax);		
	$this->world_size=$aMax-$aMin;		
	$this->InitConstants($aImg);					
    }
	
    // Translate between world and screen
    function Translate($aCoord) {
	if( !is_numeric($aCoord) ) {
	    if( $aCoord != '' && $aCoord != '-' && $aCoord != 'x' ) 
		JpGraphError::RaiseL(25070);//('Your data contains non-numeric values.');
	    return 0;
	}
	else {
	    return $this->off + ($aCoord - $this->scale[0])*$this->scale_factor;
	}
    }
	
    // Relative translate (don't include offset) usefull when we just want
    // to know the relative position (in pixels) on the axis
    function RelTranslate($aCoord) {
	if( !is_numeric($aCoord) ) {
	    if( $aCoord != '' && $aCoord != '-' && $aCoord != 'x'  ) 
		JpGraphError::RaiseL(25070);//('Your data contains non-numeric values.');
	    return 0;
	}
	else { 
	    return ($aCoord - $this->scale[0]) * $this->scale_factor; 
	}
    }
	
    // Restrict autoscaling to only use integers
    function SetIntScale($aIntScale=true) {
	$this->intscale=$aIntScale;
    }
	
    // Calculate an integer autoscale
    function IntAutoScale(&$img,$min,$max,$maxsteps,$majend=true) {
	// Make sure limits are integers
	$min=floor($min);
	$max=ceil($max);
	if( abs($min-$max)==0 ) {
	    --$min; ++$max;
	}
	$maxsteps = floor($maxsteps);
		
	$gracetop=round(($this->gracetop/100.0)*abs($max-$min));
	$gracebottom=round(($this->gracebottom/100.0)*abs($max-$min));
	if( is_numeric($this->autoscale_min) ) {
	    $min = ceil($this->autoscale_min);
	    if( $min >= $max ) {
		JpGraphError::RaiseL(25071);//('You have specified a min value with SetAutoMin() which is larger than the maximum value used for the scale. This is not possible.');
	    }
	}

	if( is_numeric($this->autoscale_max) ) {
	    $max = ceil($this->autoscale_max);
	    if( $min >= $max ) {
		JpGraphError::RaiseL(25072);//('You have specified a max value with SetAutoMax() which is smaller than the miminum value used for the scale. This is not possible.');
	    }
	}

	if( abs($min-$max ) == 0 ) {
	    ++$max;
	    --$min;
	}
			
	$min -= $gracebottom;
	$max += $gracetop;		

	// First get tickmarks as multiples of 1, 10, ...	
	if( $majend ) {
	    list($num1steps,$adj1min,$adj1max,$maj1step) = 
		$this->IntCalcTicks($maxsteps,$min,$max,1);
	}
	else {
	    $adj1min = $min;
	    $adj1max = $max;
	    list($num1steps,$maj1step) = 
		$this->IntCalcTicksFreeze($maxsteps,$min,$max,1);
	}

	if( abs($min-$max) > 2 ) {
	    // Then get tick marks as 2:s 2, 20, ...
	    if( $majend ) {
		list($num2steps,$adj2min,$adj2max,$maj2step) = 
		    $this->IntCalcTicks($maxsteps,$min,$max,5);
	    }
	    else {
		$adj2min = $min;
		$adj2max = $max;
		list($num2steps,$maj2step) = 
		    $this->IntCalcTicksFreeze($maxsteps,$min,$max,5);
	    }
	}
	else {
	    $num2steps = 10000;	// Dummy high value so we don't choose this
	}
	
	if( abs($min-$max) > 5 ) {	
	    // Then get tickmarks as 5:s 5, 50, 500, ...
	    if( $majend ) {
		list($num5steps,$adj5min,$adj5max,$maj5step) = 
		    $this->IntCalcTicks($maxsteps,$min,$max,2);
	    }
	    else {
		$adj5min = $min;
		$adj5max = $max;
		list($num5steps,$maj5step) = 
		    $this->IntCalcTicksFreeze($maxsteps,$min,$max,2);
	    }
	}
	else {
	    $num5steps = 10000;	// Dummy high value so we don't choose this		
	}
	
	// Check to see whichof 1:s, 2:s or 5:s fit better with
	// the requested number of major ticks		
	$match1=abs($num1steps-$maxsteps);		
	$match2=abs($num2steps-$maxsteps);
	if( !empty($maj5step) && $maj5step > 1 )
	    $match5=abs($num5steps-$maxsteps);
	else
	    $match5=10000; 	// Dummy high value 
		
	// Compare these three values and see which is the closest match
	// We use a 0.6 weight to gravitate towards multiple of 5:s 
	if( $match1 < $match2 ) {
	    if( $match1 < $match5 )
		$r=1;			
	    else 
		$r=3;
	}
	else {
	    if( $match2 < $match5 )
		$r=2;			
	    else 
		$r=3;		
	}	
	// Minsteps are always the same as maxsteps for integer scale
	switch( $r ) {
	    case 1:
		$this->ticks->Set($maj1step,$maj1step);
		$this->Update($img,$adj1min,$adj1max);
		break;			
	    case 2:
		$this->ticks->Set($maj2step,$maj2step);
		$this->Update($img,$adj2min,$adj2max);		
		break;									
	    case 3:
		$this->ticks->Set($maj5step,$maj5step);		
		$this->Update($img,$adj5min,$adj5max);
		break;	
	    default:
		JpGraphError::RaiseL(25073,$r);//('Internal error. Integer scale algorithm comparison out of bound (r=$r)');
	}		
    }
	
	
    // Calculate autoscale. Used if user hasn't given a scale and ticks
    // $maxsteps is the maximum number of major tickmarks allowed.
    function AutoScale(&$img,$min,$max,$maxsteps,$majend=true) {
	if( $this->intscale ) {	
	    $this->IntAutoScale($img,$min,$max,$maxsteps,$majend);
	    return;
	}
	if( abs($min-$max) < 0.00001 ) {
	    // We need some difference to be able to autoscale
	    // make it 5% above and 5% below value
	    if( $min==0 && $max==0 ) {		// Special case
		$min=-1; $max=1;
	    }
	    else {
		$delta = (abs($max)+abs($min))*0.005;
		$min -= $delta;
		$max += $delta;
	    }
	}
		
	$gracetop=($this->gracetop/100.0)*abs($max-$min);
	$gracebottom=($this->gracebottom/100.0)*abs($max-$min);
	if( is_numeric($this->autoscale_min) ) {
	    $min = $this->autoscale_min;
	    if( $min >= $max ) {
		JpGraphError::RaiseL(25071);//('You have specified a min value with SetAutoMin() which is larger than the maximum value used for the scale. This is not possible.');
	    }
	    if( abs($min-$max ) < 0.00001 )
		$max *= 1.2;
	}

	if( is_numeric($this->autoscale_max) ) {
	    $max = $this->autoscale_max;
	    if( $min >= $max ) {
		JpGraphError::RaiseL(25072);//('You have specified a max value with SetAutoMax() which is smaller than the miminum value used for the scale. This is not possible.');
	    }
	    if( abs($min-$max ) < 0.00001 )
		$min *= 0.8;
	}

	
	$min -= $gracebottom;
	$max += $gracetop;

	// First get tickmarks as multiples of 0.1, 1, 10, ...	
	if( $majend ) {
	    list($num1steps,$adj1min,$adj1max,$min1step,$maj1step) = 
		$this->CalcTicks($maxsteps,$min,$max,1,2);
	}
	else {
	    $adj1min=$min;
	    $adj1max=$max;
	    list($num1steps,$min1step,$maj1step) = 
		$this->CalcTicksFreeze($maxsteps,$min,$max,1,2,false);
	}
		
	// Then get tick marks as 2:s 0.2, 2, 20, ...
	if( $majend ) {
	    list($num2steps,$adj2min,$adj2max,$min2step,$maj2step) = 
		$this->CalcTicks($maxsteps,$min,$max,5,2);
	}
	else {
	    $adj2min=$min;
	    $adj2max=$max;
	    list($num2steps,$min2step,$maj2step) = 
		$this->CalcTicksFreeze($maxsteps,$min,$max,5,2,false);
	}
		
	// Then get tickmarks as 5:s 0.05, 0.5, 5, 50, ...
	if( $majend ) {
	    list($num5steps,$adj5min,$adj5max,$min5step,$maj5step) = 
		$this->CalcTicks($maxsteps,$min,$max,2,5);		
	}
	else {
	    $adj5min=$min;
	    $adj5max=$max;
	    list($num5steps,$min5step,$maj5step) = 
		$this->CalcTicksFreeze($maxsteps,$min,$max,2,5,false);
	}

	// Check to see whichof 1:s, 2:s or 5:s fit better with
	// the requested number of major ticks		
	$match1=abs($num1steps-$maxsteps);		
	$match2=abs($num2steps-$maxsteps);
	$match5=abs($num5steps-$maxsteps);
	// Compare these three values and see which is the closest match
	// We use a 0.8 weight to gravitate towards multiple of 5:s 
	$r=$this->MatchMin3($match1,$match2,$match5,0.8);
	switch( $r ) {
	    case 1:
		$this->Update($img,$adj1min,$adj1max);
		$this->ticks->Set($maj1step,$min1step);
		break;			
	    case 2:
		$this->Update($img,$adj2min,$adj2max);		
		$this->ticks->Set($maj2step,$min2step);
		break;									
	    case 3:
		$this->Update($img,$adj5min,$adj5max);
		$this->ticks->Set($maj5step,$min5step);		
		break;			
	}
    }

//---------------
// PRIVATE METHODS	

    // This method recalculates all constants that are depending on the
    // margins in the image. If the margins in the image are changed
    // this method should be called for every scale that is registred with
    // that image. Should really be installed as an observer of that image.
    function InitConstants(&$img) {
	if( $this->type=="x" ) {
	    $this->world_abs_size=$img->width - $img->left_margin - $img->right_margin;
	    $this->off=$img->left_margin;
	    $this->scale_factor = 0;
	    if( $this->world_size > 0 )
		$this->scale_factor=$this->world_abs_size/($this->world_size*1.0);
	}
	else { // y scale
	    $this->world_abs_size=$img->height - $img->top_margin - $img->bottom_margin; 
	    $this->off=$img->top_margin+$this->world_abs_size;			
	    $this->scale_factor = 0;			
	    if( $this->world_size > 0 ) {
		$this->scale_factor=-$this->world_abs_size/($this->world_size*1.0);	
	    }
	}
	$size = $this->world_size * $this->scale_factor;
	$this->scale_abs=array($this->off,$this->off + $size);	
    }
	
    // Initialize the conversion constants for this scale
    // This tries to pre-calculate as much as possible to speed up the
    // actual conversion (with Translate()) later on
    // $start	=scale start in absolute pixels (for x-scale this is an y-position
    //				 and for an y-scale this is an x-position
    // $len 		=absolute length in pixels of scale 			
    function SetConstants($aStart,$aLen) {
	$this->world_abs_size=$aLen;
	$this->off=$aStart;
		
	if( $this->world_size<=0 ) {
	    // This should never ever happen !!
	    JpGraphError::RaiseL(25074);
//("You have unfortunately stumbled upon a bug in JpGraph. It seems like the scale range is ".$this->world_size." [for ".$this->type." scale] <br> Please report Bug #01 to jpgraph@aditus.nu and include the script that gave this error. This problem could potentially be caused by trying to use \"illegal\" values in the input data arrays (like trying to send in strings or only NULL values) which causes the autoscaling to fail.");

	}
		
	// scale_factor = number of pixels per world unit
	$this->scale_factor=$this->world_abs_size/($this->world_size*1.0);
		
	// scale_abs = start and end points of scale in absolute pixels
	$this->scale_abs=array($this->off,$this->off+$this->world_size*$this->scale_factor);		
    }
	
	
    // Calculate number of ticks steps with a specific division
    // $a is the divisor of 10**x to generate the first maj tick intervall
    // $a=1, $b=2 give major ticks with multiple of 10, ...,0.1,1,10,...
    // $a=5, $b=2 give major ticks with multiple of 2:s ...,0.2,2,20,...
    // $a=2, $b=5 give major ticks with multiple of 5:s ...,0.5,5,50,...
    // We return a vector of
    // 	[$numsteps,$adjmin,$adjmax,$minstep,$majstep]
    // If $majend==true then the first and last marks on the axis will be major
    // labeled tick marks otherwise it will be adjusted to the closest min tick mark
    function CalcTicks($maxsteps,$min,$max,$a,$b,$majend=true) {
	$diff=$max-$min; 
	if( $diff==0 )
	    $ld=0;
	else
	    $ld=floor(log10($diff));

	// Gravitate min towards zero if we are close		
	if( $min>0 && $min < pow(10,$ld) ) $min=0;
		
	//$majstep=pow(10,$ld-1)/$a; 
	$majstep=pow(10,$ld)/$a; 
	$minstep=$majstep/$b;
	
	$adjmax=ceil($max/$minstep)*$minstep;
	$adjmin=floor($min/$minstep)*$minstep;	
	$adjdiff = $adjmax-$adjmin;
	$numsteps=$adjdiff/$majstep; 
	
	while( $numsteps>$maxsteps ) {
	    $majstep=pow(10,$ld)/$a; 
	    $numsteps=$adjdiff/$majstep;
	    ++$ld;
	}

	$minstep=$majstep/$b;
	$adjmin=floor($min/$minstep)*$minstep;	
	$adjdiff = $adjmax-$adjmin;		
	if( $majend ) {
	    $adjmin = floor($min/$majstep)*$majstep;	
	    $adjdiff = $adjmax-$adjmin;		
	    $adjmax = ceil($adjdiff/$majstep)*$majstep+$adjmin;
	}
	else
	    $adjmax=ceil($max/$minstep)*$minstep;

	return array($numsteps,$adjmin,$adjmax,$minstep,$majstep);
    }

    function CalcTicksFreeze($maxsteps,$min,$max,$a,$b) {
	// Same as CalcTicks but don't adjust min/max values
	$diff=$max-$min; 
	if( $diff==0 )
	    $ld=0;
	else
	    $ld=floor(log10($diff));

	//$majstep=pow(10,$ld-1)/$a; 
	$majstep=pow(10,$ld)/$a; 
	$minstep=$majstep/$b;
	$numsteps=floor($diff/$majstep); 
	
	while( $numsteps > $maxsteps ) {
	    $majstep=pow(10,$ld)/$a; 
	    $numsteps=floor($diff/$majstep);
	    ++$ld;
	}
	$minstep=$majstep/$b;
	return array($numsteps,$minstep,$majstep);
    }

	
    function IntCalcTicks($maxsteps,$min,$max,$a,$majend=true) {
	$diff=$max-$min; 
	if( $diff==0 )
	    JpGraphError::RaiseL(25075);//('Can\'t automatically determine ticks since min==max.');
	else
	    $ld=floor(log10($diff));
		
	// Gravitate min towards zero if we are close		
	if( $min>0 && $min < pow(10,$ld) ) $min=0;
		
	if( $ld == 0 ) $ld=1;
	
	if( $a == 1 ) 
	    $majstep = 1;
	else
	    $majstep=pow(10,$ld)/$a; 
	$adjmax=ceil($max/$majstep)*$majstep;

	$adjmin=floor($min/$majstep)*$majstep;	
	$adjdiff = $adjmax-$adjmin;
	$numsteps=$adjdiff/$majstep; 
	while( $numsteps>$maxsteps ) {
	    $majstep=pow(10,$ld)/$a; 
	    $numsteps=$adjdiff/$majstep;
	    ++$ld;
	}
		
	$adjmin=floor($min/$majstep)*$majstep;	
	$adjdiff = $adjmax-$adjmin;		
	if( $majend ) {
	    $adjmin = floor($min/$majstep)*$majstep;	
	    $adjdiff = $adjmax-$adjmin;		
	    $adjmax = ceil($adjdiff/$majstep)*$majstep+$adjmin;
	}
	else
	    $adjmax=ceil($max/$majstep)*$majstep;
			
	return array($numsteps,$adjmin,$adjmax,$majstep);		
    }


    function IntCalcTicksFreeze($maxsteps,$min,$max,$a) {
	// Same as IntCalcTick but don't change min/max values
	$diff=$max-$min; 
	if( $diff==0 )
	    JpGraphError::RaiseL(25075);//('Can\'t automatically determine ticks since min==max.');
	else
	    $ld=floor(log10($diff));
		
	if( $ld == 0 ) $ld=1;
	
	if( $a == 1 ) 
	    $majstep = 1;
	else
	    $majstep=pow(10,$ld)/$a; 

	$numsteps=floor($diff/$majstep); 
	while( $numsteps > $maxsteps ) {
	    $majstep=pow(10,$ld)/$a; 
	    $numsteps=floor($diff/$majstep);
	    ++$ld;
	}
					
	return array($numsteps,$majstep);		
    }


	
    // Determine the minimum of three values witha  weight for last value
    function MatchMin3($a,$b,$c,$weight) {
	if( $a < $b ) {
	    if( $a < ($c*$weight) ) 
		return 1; // $a smallest
	    else 
		return 3; // $c smallest
	}
	elseif( $b < ($c*$weight) ) 
	    return 2; // $b smallest
	return 3; // $c smallest
    }
} // Class

//===================================================
// CLASS RGB
// Description: Color definitions as RGB triples
//===================================================
class RGB {
    var $rgb_table;
    var $img;
    function RGB(&$aImg) {
	$this->img = &$aImg;
		
	// Conversion array between color names and RGB
	$this->rgb_table = array(
	    "aqua"=> array(0,255,255),		
	    "lime"=> array(0,255,0),		
	    "teal"=> array(0,128,128),
	    "whitesmoke"=>array(245,245,245),
	    "gainsboro"=>array(220,220,220),
	    "oldlace"=>array(253,245,230),
	    "linen"=>array(250,240,230),
	    "antiquewhite"=>array(250,235,215),
	    "papayawhip"=>array(255,239,213),
	    "blanchedalmond"=>array(255,235,205),
	    "bisque"=>array(255,228,196),
	    "peachpuff"=>array(255,218,185),
	    "navajowhite"=>array(255,222,173),
	    "moccasin"=>array(255,228,181),
	    "cornsilk"=>array(255,248,220),
	    "ivory"=>array(255,255,240),
	    "lemonchiffon"=>array(255,250,205),
	    "seashell"=>array(255,245,238),
	    "mintcream"=>array(245,255,250),
	    "azure"=>array(240,255,255),
	    "aliceblue"=>array(240,248,255),
	    "lavender"=>array(230,230,250),
	    "lavenderblush"=>array(255,240,245),
	    "mistyrose"=>array(255,228,225),
	    "white"=>array(255,255,255),
	    "black"=>array(0,0,0),
	    "darkslategray"=>array(47,79,79),
	    "dimgray"=>array(105,105,105),
	    "slategray"=>array(112,128,144),
	    "lightslategray"=>array(119,136,153),
	    "gray"=>array(190,190,190),
	    "lightgray"=>array(211,211,211),
	    "midnightblue"=>array(25,25,112),
	    "navy"=>array(0,0,128),
	    "cornflowerblue"=>array(100,149,237),
	    "darkslateblue"=>array(72,61,139),
	    "slateblue"=>array(106,90,205),
	    "mediumslateblue"=>array(123,104,238),
	    "lightslateblue"=>array(132,112,255),
	    "mediumblue"=>array(0,0,205),
	    "royalblue"=>array(65,105,225),
	    "blue"=>array(0,0,255),
	    "dodgerblue"=>array(30,144,255),
	    "deepskyblue"=>array(0,191,255),
	    "skyblue"=>array(135,206,235),
	    "lightskyblue"=>array(135,206,250),
	    "steelblue"=>array(70,130,180),
	    "lightred"=>array(211,167,168),
	    "lightsteelblue"=>array(176,196,222),
	    "lightblue"=>array(173,216,230),
	    "powderblue"=>array(176,224,230),
	    "paleturquoise"=>array(175,238,238),
	    "darkturquoise"=>array(0,206,209),
	    "mediumturquoise"=>array(72,209,204),
	    "turquoise"=>array(64,224,208),
	    "cyan"=>array(0,255,255),
	    "lightcyan"=>array(224,255,255),
	    "cadetblue"=>array(95,158,160),
	    "mediumaquamarine"=>array(102,205,170),
	    "aquamarine"=>array(127,255,212),
	    "darkgreen"=>array(0,100,0),
	    "darkolivegreen"=>array(85,107,47),
	    "darkseagreen"=>array(143,188,143),
	    "seagreen"=>array(46,139,87),
	    "mediumseagreen"=>array(60,179,113),
	    "lightseagreen"=>array(32,178,170),
	    "palegreen"=>array(152,251,152),
	    "springgreen"=>array(0,255,127),
	    "lawngreen"=>array(124,252,0),
	    "green"=>array(0,255,0),
	    "chartreuse"=>array(127,255,0),
	    "mediumspringgreen"=>array(0,250,154),
	    "greenyellow"=>array(173,255,47),
	    "limegreen"=>array(50,205,50),
	    "yellowgreen"=>array(154,205,50),
	    "forestgreen"=>array(34,139,34),
	    "olivedrab"=>array(107,142,35),
	    "darkkhaki"=>array(189,183,107),
	    "khaki"=>array(240,230,140),
	    "palegoldenrod"=>array(238,232,170),
	    "lightgoldenrodyellow"=>array(250,250,210),
	    "lightyellow"=>array(255,255,200),
	    "yellow"=>array(255,255,0),
	    "gold"=>array(255,215,0),
	    "lightgoldenrod"=>array(238,221,130),
	    "goldenrod"=>array(218,165,32),
	    "darkgoldenrod"=>array(184,134,11),
	    "rosybrown"=>array(188,143,143),
	    "indianred"=>array(205,92,92),
	    "saddlebrown"=>array(139,69,19),
	    "sienna"=>array(160,82,45),
	    "peru"=>array(205,133,63),
	    "burlywood"=>array(222,184,135),
	    "beige"=>array(245,245,220),
	    "wheat"=>array(245,222,179),
	    "sandybrown"=>array(244,164,96),
	    "tan"=>array(210,180,140),
	    "chocolate"=>array(210,105,30),
	    "firebrick"=>array(178,34,34),
	    "brown"=>array(165,42,42),
	    "darksalmon"=>array(233,150,122),
	    "salmon"=>array(250,128,114),
	    "lightsalmon"=>array(255,160,122),
	    "orange"=>array(255,165,0),
	    "darkorange"=>array(255,140,0),
	    "coral"=>array(255,127,80),
	    "lightcoral"=>array(240,128,128),
	    "tomato"=>array(255,99,71),
	    "orangered"=>array(255,69,0),
	    "red"=>array(255,0,0),
	    "hotpink"=>array(255,105,180),
	    "deeppink"=>array(255,20,147),
	    "pink"=>array(255,192,203),
	    "lightpink"=>array(255,182,193),
	    "palevioletred"=>array(219,112,147),
	    "maroon"=>array(176,48,96),
	    "mediumvioletred"=>array(199,21,133),
	    "violetred"=>array(208,32,144),
	    "magenta"=>array(255,0,255),
	    "violet"=>array(238,130,238),
	    "plum"=>array(221,160,221),
	    "orchid"=>array(218,112,214),
	    "mediumorchid"=>array(186,85,211),
	    "darkorchid"=>array(153,50,204),
	    "darkviolet"=>array(148,0,211),
	    "blueviolet"=>array(138,43,226),
	    "purple"=>array(160,32,240),
	    "mediumpurple"=>array(147,112,219),
	    "thistle"=>array(216,191,216),
	    "snow1"=>array(255,250,250),
	    "snow2"=>array(238,233,233),
	    "snow3"=>array(205,201,201),
	    "snow4"=>array(139,137,137),
	    "seashell1"=>array(255,245,238),
	    "seashell2"=>array(238,229,222),
	    "seashell3"=>array(205,197,191),
	    "seashell4"=>array(139,134,130),
	    "AntiqueWhite1"=>array(255,239,219),
	    "AntiqueWhite2"=>array(238,223,204),
	    "AntiqueWhite3"=>array(205,192,176),
	    "AntiqueWhite4"=>array(139,131,120),
	    "bisque1"=>array(255,228,196),
	    "bisque2"=>array(238,213,183),
	    "bisque3"=>array(205,183,158),
	    "bisque4"=>array(139,125,107),
	    "peachPuff1"=>array(255,218,185),
	    "peachpuff2"=>array(238,203,173),
	    "peachpuff3"=>array(205,175,149),
	    "peachpuff4"=>array(139,119,101),
	    "navajowhite1"=>array(255,222,173),
	    "navajowhite2"=>array(238,207,161),
	    "navajowhite3"=>array(205,179,139),
	    "navajowhite4"=>array(139,121,94),
	    "lemonchiffon1"=>array(255,250,205),
	    "lemonchiffon2"=>array(238,233,191),
	    "lemonchiffon3"=>array(205,201,165),
	    "lemonchiffon4"=>array(139,137,112),
	    "ivory1"=>array(255,255,240),
	    "ivory2"=>array(238,238,224),
	    "ivory3"=>array(205,205,193),
	    "ivory4"=>array(139,139,131),
	    "honeydew"=>array(193,205,193),
	    "lavenderblush1"=>array(255,240,245),
	    "lavenderblush2"=>array(238,224,229),
	    "lavenderblush3"=>array(205,193,197),
	    "lavenderblush4"=>array(139,131,134),
	    "mistyrose1"=>array(255,228,225),
	    "mistyrose2"=>array(238,213,210),
	    "mistyrose3"=>array(205,183,181),
	    "mistyrose4"=>array(139,125,123),
	    "azure1"=>array(240,255,255),
	    "azure2"=>array(224,238,238),
	    "azure3"=>array(193,205,205),
	    "azure4"=>array(131,139,139),
	    "slateblue1"=>array(131,111,255),
	    "slateblue2"=>array(122,103,238),
	    "slateblue3"=>array(105,89,205),
	    "slateblue4"=>array(71,60,139),
	    "royalblue1"=>array(72,118,255),
	    "royalblue2"=>array(67,110,238),
	    "royalblue3"=>array(58,95,205),
	    "royalblue4"=>array(39,64,139),
	    "dodgerblue1"=>array(30,144,255),
	    "dodgerblue2"=>array(28,134,238),
	    "dodgerblue3"=>array(24,116,205),
	    "dodgerblue4"=>array(16,78,139),
	    "steelblue1"=>array(99,184,255),
	    "steelblue2"=>array(92,172,238),
	    "steelblue3"=>array(79,148,205),
	    "steelblue4"=>array(54,100,139),
	    "deepskyblue1"=>array(0,191,255),
	    "deepskyblue2"=>array(0,178,238),
	    "deepskyblue3"=>array(0,154,205),
	    "deepskyblue4"=>array(0,104,139),
	    "skyblue1"=>array(135,206,255),
	    "skyblue2"=>array(126,192,238),
	    "skyblue3"=>array(108,166,205),
	    "skyblue4"=>array(74,112,139),
	    "lightskyblue1"=>array(176,226,255),
	    "lightskyblue2"=>array(164,211,238),
	    "lightskyblue3"=>array(141,182,205),
	    "lightskyblue4"=>array(96,123,139),
	    "slategray1"=>array(198,226,255),
	    "slategray2"=>array(185,211,238),
	    "slategray3"=>array(159,182,205),
	    "slategray4"=>array(108,123,139),
	    "lightsteelblue1"=>array(202,225,255),
	    "lightsteelblue2"=>array(188,210,238),
	    "lightsteelblue3"=>array(162,181,205),
	    "lightsteelblue4"=>array(110,123,139),
	    "lightblue1"=>array(191,239,255),
	    "lightblue2"=>array(178,223,238),
	    "lightblue3"=>array(154,192,205),
	    "lightblue4"=>array(104,131,139),
	    "lightcyan1"=>array(224,255,255),
	    "lightcyan2"=>array(209,238,238),
	    "lightcyan3"=>array(180,205,205),
	    "lightcyan4"=>array(122,139,139),
	    "paleturquoise1"=>array(187,255,255),
	    "paleturquoise2"=>array(174,238,238),
	    "paleturquoise3"=>array(150,205,205),
	    "paleturquoise4"=>array(102,139,139),
	    "cadetblue1"=>array(152,245,255),
	    "cadetblue2"=>array(142,229,238),
	    "cadetblue3"=>array(122,197,205),
	    "cadetblue4"=>array(83,134,139),
	    "turquoise1"=>array(0,245,255),
	    "turquoise2"=>array(0,229,238),
	    "turquoise3"=>array(0,197,205),
	    "turquoise4"=>array(0,134,139),
	    "cyan1"=>array(0,255,255),
	    "cyan2"=>array(0,238,238),
	    "cyan3"=>array(0,205,205),
	    "cyan4"=>array(0,139,139),
	    "darkslategray1"=>array(151,255,255),
	    "darkslategray2"=>array(141,238,238),
	    "darkslategray3"=>array(121,205,205),
	    "darkslategray4"=>array(82,139,139),
	    "aquamarine1"=>array(127,255,212),
	    "aquamarine2"=>array(118,238,198),
	    "aquamarine3"=>array(102,205,170),
	    "aquamarine4"=>array(69,139,116),
	    "darkseagreen1"=>array(193,255,193),
	    "darkseagreen2"=>array(180,238,180),
	    "darkseagreen3"=>array(155,205,155),
	    "darkseagreen4"=>array(105,139,105),
	    "seagreen1"=>array(84,255,159),
	    "seagreen2"=>array(78,238,148),
	    "seagreen3"=>array(67,205,128),
	    "seagreen4"=>array(46,139,87),
	    "palegreen1"=>array(154,255,154),
	    "palegreen2"=>array(144,238,144),
	    "palegreen3"=>array(124,205,124),
	    "palegreen4"=>array(84,139,84),
	    "springgreen1"=>array(0,255,127),
	    "springgreen2"=>array(0,238,118),
	    "springgreen3"=>array(0,205,102),
	    "springgreen4"=>array(0,139,69),
	    "chartreuse1"=>array(127,255,0),
	    "chartreuse2"=>array(118,238,0),
	    "chartreuse3"=>array(102,205,0),
	    "chartreuse4"=>array(69,139,0),
	    "olivedrab1"=>array(192,255,62),
	    "olivedrab2"=>array(179,238,58),
	    "olivedrab3"=>array(154,205,50),
	    "olivedrab4"=>array(105,139,34),
	    "darkolivegreen1"=>array(202,255,112),
	    "darkolivegreen2"=>array(188,238,104),
	    "darkolivegreen3"=>array(162,205,90),
	    "darkolivegreen4"=>array(110,139,61),
	    "khaki1"=>array(255,246,143),
	    "khaki2"=>array(238,230,133),
	    "khaki3"=>array(205,198,115),
	    "khaki4"=>array(139,134,78),
	    "lightgoldenrod1"=>array(255,236,139),
	    "lightgoldenrod2"=>array(238,220,130),
	    "lightgoldenrod3"=>array(205,190,112),
	    "lightgoldenrod4"=>array(139,129,76),
	    "yellow1"=>array(255,255,0),
	    "yellow2"=>array(238,238,0),
	    "yellow3"=>array(205,205,0),
	    "yellow4"=>array(139,139,0),
	    "gold1"=>array(255,215,0),
	    "gold2"=>array(238,201,0),
	    "gold3"=>array(205,173,0),
	    "gold4"=>array(139,117,0),
	    "goldenrod1"=>array(255,193,37),
	    "goldenrod2"=>array(238,180,34),
	    "goldenrod3"=>array(205,155,29),
	    "goldenrod4"=>array(139,105,20),
	    "darkgoldenrod1"=>array(255,185,15),
	    "darkgoldenrod2"=>array(238,173,14),
	    "darkgoldenrod3"=>array(205,149,12),
	    "darkgoldenrod4"=>array(139,101,8),
	    "rosybrown1"=>array(255,193,193),
	    "rosybrown2"=>array(238,180,180),
	    "rosybrown3"=>array(205,155,155),
	    "rosybrown4"=>array(139,105,105),
	    "indianred1"=>array(255,106,106),
	    "indianred2"=>array(238,99,99),
	    "indianred3"=>array(205,85,85),
	    "indianred4"=>array(139,58,58),
	    "sienna1"=>array(255,130,71),
	    "sienna2"=>array(238,121,66),
	    "sienna3"=>array(205,104,57),
	    "sienna4"=>array(139,71,38),
	    "burlywood1"=>array(255,211,155),
	    "burlywood2"=>array(238,197,145),
	    "burlywood3"=>array(205,170,125),
	    "burlywood4"=>array(139,115,85),
	    "wheat1"=>array(255,231,186),
	    "wheat2"=>array(238,216,174),
	    "wheat3"=>array(205,186,150),
	    "wheat4"=>array(139,126,102),
	    "tan1"=>array(255,165,79),
	    "tan2"=>array(238,154,73),
	    "tan3"=>array(205,133,63),
	    "tan4"=>array(139,90,43),
	    "chocolate1"=>array(255,127,36),
	    "chocolate2"=>array(238,118,33),
	    "chocolate3"=>array(205,102,29),
	    "chocolate4"=>array(139,69,19),
	    "firebrick1"=>array(255,48,48),
	    "firebrick2"=>array(238,44,44),
	    "firebrick3"=>array(205,38,38),
	    "firebrick4"=>array(139,26,26),
	    "brown1"=>array(255,64,64),
	    "brown2"=>array(238,59,59),
	    "brown3"=>array(205,51,51),
	    "brown4"=>array(139,35,35),
	    "salmon1"=>array(255,140,105),
	    "salmon2"=>array(238,130,98),
	    "salmon3"=>array(205,112,84),
	    "salmon4"=>array(139,76,57),
	    "lightsalmon1"=>array(255,160,122),
	    "lightsalmon2"=>array(238,149,114),
	    "lightsalmon3"=>array(205,129,98),
	    "lightsalmon4"=>array(139,87,66),
	    "orange1"=>array(255,165,0),
	    "orange2"=>array(238,154,0),
	    "orange3"=>array(205,133,0),
	    "orange4"=>array(139,90,0),
	    "darkorange1"=>array(255,127,0),
	    "darkorange2"=>array(238,118,0),
	    "darkorange3"=>array(205,102,0),
	    "darkorange4"=>array(139,69,0),
	    "coral1"=>array(255,114,86),
	    "coral2"=>array(238,106,80),
	    "coral3"=>array(205,91,69),
	    "coral4"=>array(139,62,47),
	    "tomato1"=>array(255,99,71),
	    "tomato2"=>array(238,92,66),
	    "tomato3"=>array(205,79,57),
	    "tomato4"=>array(139,54,38),
	    "orangered1"=>array(255,69,0),
	    "orangered2"=>array(238,64,0),
	    "orangered3"=>array(205,55,0),
	    "orangered4"=>array(139,37,0),
	    "deeppink1"=>array(255,20,147),
	    "deeppink2"=>array(238,18,137),
	    "deeppink3"=>array(205,16,118),
	    "deeppink4"=>array(139,10,80),
	    "hotpink1"=>array(255,110,180),
	    "hotpink2"=>array(238,106,167),
	    "hotpink3"=>array(205,96,144),
	    "hotpink4"=>array(139,58,98),
	    "pink1"=>array(255,181,197),
	    "pink2"=>array(238,169,184),
	    "pink3"=>array(205,145,158),
	    "pink4"=>array(139,99,108),
	    "lightpink1"=>array(255,174,185),
	    "lightpink2"=>array(238,162,173),
	    "lightpink3"=>array(205,140,149),
	    "lightpink4"=>array(139,95,101),
	    "palevioletred1"=>array(255,130,171),
	    "palevioletred2"=>array(238,121,159),
	    "palevioletred3"=>array(205,104,137),
	    "palevioletred4"=>array(139,71,93),
	    "maroon1"=>array(255,52,179),
	    "maroon2"=>array(238,48,167),
	    "maroon3"=>array(205,41,144),
	    "maroon4"=>array(139,28,98),
	    "violetred1"=>array(255,62,150),
	    "violetred2"=>array(238,58,140),
	    "violetred3"=>array(205,50,120),
	    "violetred4"=>array(139,34,82),
	    "magenta1"=>array(255,0,255),
	    "magenta2"=>array(238,0,238),
	    "magenta3"=>array(205,0,205),
	    "magenta4"=>array(139,0,139),
	    "mediumred"=>array(140,34,34),         
	    "orchid1"=>array(255,131,250),
	    "orchid2"=>array(238,122,233),
	    "orchid3"=>array(205,105,201),
	    "orchid4"=>array(139,71,137),
	    "plum1"=>array(255,187,255),
	    "plum2"=>array(238,174,238),
	    "plum3"=>array(205,150,205),
	    "plum4"=>array(139,102,139),
	    "mediumorchid1"=>array(224,102,255),
	    "mediumorchid2"=>array(209,95,238),
	    "mediumorchid3"=>array(180,82,205),
	    "mediumorchid4"=>array(122,55,139),
	    "darkorchid1"=>array(191,62,255),
	    "darkorchid2"=>array(178,58,238),
	    "darkorchid3"=>array(154,50,205),
	    "darkorchid4"=>array(104,34,139),
	    "purple1"=>array(155,48,255),
	    "purple2"=>array(145,44,238),
	    "purple3"=>array(125,38,205),
	    "purple4"=>array(85,26,139),
	    "mediumpurple1"=>array(171,130,255),
	    "mediumpurple2"=>array(159,121,238),
	    "mediumpurple3"=>array(137,104,205),
	    "mediumpurple4"=>array(93,71,139),
	    "thistle1"=>array(255,225,255),
	    "thistle2"=>array(238,210,238),
	    "thistle3"=>array(205,181,205),
	    "thistle4"=>array(139,123,139),
	    "gray1"=>array(10,10,10),
	    "gray2"=>array(40,40,30),
	    "gray3"=>array(70,70,70),
	    "gray4"=>array(100,100,100),
	    "gray5"=>array(130,130,130),
	    "gray6"=>array(160,160,160),
	    "gray7"=>array(190,190,190),
	    "gray8"=>array(210,210,210),
	    "gray9"=>array(240,240,240),
	    "darkgray"=>array(100,100,100),
	    "darkblue"=>array(0,0,139),
	    "darkcyan"=>array(0,139,139),
	    "darkmagenta"=>array(139,0,139),
	    "darkred"=>array(139,0,0),
	    "silver"=>array(192, 192, 192),
	    "eggplant"=>array(144,176,168),
	    "lightgreen"=>array(144,238,144));		
    }
//----------------
// PUBLIC METHODS
    // Colors can be specified as either
    // 1. #xxxxxx			HTML style
    // 2. "colorname" 	as a named color
    // 3. array(r,g,b)	RGB triple
    // This function translates this to a native RGB format and returns an 
    // RGB triple.
    function Color($aColor) {
	if (is_string($aColor)) {
	    // Strip of any alpha factor
	    $pos = strpos($aColor,'@');
	    if( $pos === false ) {
		$alpha = 0;
	    }
	    else {
		$pos2 = strpos($aColor,':');
		if( $pos2===false ) 
		    $pos2 = $pos-1; // Sentinel
		if( $pos > $pos2 ) {
		    $alpha = substr($aColor,$pos+1);
		    $aColor = substr($aColor,0,$pos);
		}
		else {
		    $alpha = substr($aColor,$pos+1,$pos2-$pos-1);
		    $aColor = substr($aColor,0,$pos).substr($aColor,$pos2);
		}
	    }

	    // Extract potential adjustment figure at end of color
	    // specification
	    $pos = strpos($aColor,":");
	    if( $pos === false ) {
		$adj = 1.0;
	    }
	    else {
		$adj = 0.0 + substr($aColor,$pos+1);
		$aColor = substr($aColor,0,$pos);
	    }
	    if( $adj < 0 )
		JpGraphError::RaiseL(25077);//('Adjustment factor for color must be > 0');

	    if (substr($aColor, 0, 1) == "#") {
		$r = hexdec(substr($aColor, 1, 2));
		$g = hexdec(substr($aColor, 3, 2));
		$b = hexdec(substr($aColor, 5, 2));
	    } else {
      		if(!isset($this->rgb_table[$aColor]) )
		    JpGraphError::RaiseL(25078,$aColor);//(" Unknown color: $aColor");
		$tmp=$this->rgb_table[$aColor];
		$r = $tmp[0];
		$g = $tmp[1];
		$b = $tmp[2];
	    }
	    // Scale adj so that an adj=2 always
	    // makes the color 100% white (i.e. 255,255,255. 
	    // and adj=1 neutral and adj=0 black.
	    if( $adj > 1 ) {
		$m = ($adj-1.0)*(255-min(255,min($r,min($g,$b))));
		return array(min(255,$r+$m), min(255,$g+$m), min(255,$b+$m),$alpha);
	    }
	    elseif( $adj < 1 ) {
		$m = ($adj-1.0)*max(255,max($r,max($g,$b)));
		return array(max(0,$r+$m), max(0,$g+$m), max(0,$b+$m),$alpha);
	    }
	    else {
		return array($r,$g,$b,$alpha);
	    }

	} elseif( is_array($aColor) ) {
	    if( count($aColor)==3 ) {
		$aColor[3]=0;
		return $aColor;
	    }
	    else
		return $aColor;
	}
	else
	    JpGraphError::RaiseL(25079,$aColor,count($aColor));//(" Unknown color specification: $aColor , size=".count($aColor));
    }
	
    // Compare two colors
    // return true if equal
    function Equal($aCol1,$aCol2) {
	$c1 = $this->Color($aCol1);
	$c2 = $this->Color($aCol2);
	if( $c1[0]==$c2[0] && $c1[1]==$c2[1] && $c1[2]==$c2[2] )
	    return true;
	else
	    return false;
    }
	
    // Allocate a new color in the current image
    // Return new color index, -1 if no more colors could be allocated
    function Allocate($aColor,$aAlpha=0.0) {
	list ($r, $g, $b, $a) = $this->color($aColor);
	// If alpha is specified in the color string then this
	// takes precedence over the second argument
	if( $a > 0 )
	    $aAlpha = $a;
	if( $GLOBALS['gd2'] ) {
	    if( $aAlpha < 0 || $aAlpha > 1 ) {
		JpGraphError::RaiseL(25080);//('Alpha parameter for color must be between 0.0 and 1.0');
	    }
	    return imagecolorresolvealpha($this->img, $r, $g, $b, round($aAlpha * 127));
	} else {
	    $index = imagecolorexact($this->img, $r, $g, $b);
	    if ($index == -1) {
      		$index = imagecolorallocate($this->img, $r, $g, $b);
      		if( USE_APPROX_COLORS && $index == -1 )
		    $index = imagecolorresolve($this->img, $r, $g, $b);
	    } 
	    return $index;
	}
    }
} // Class

	
//===================================================
// CLASS Image
// Description: Wrapper class with some goodies to form the
// Interface to low level image drawing routines.
//===================================================
class Image {
    var $img_format;
    var $expired=true;
    var $img=null;
    var $left_margin=30,$right_margin=20,$top_margin=20,$bottom_margin=30;
    var $plotwidth=0,$plotheight=0;
    var $rgb=null;
    var $current_color,$current_color_name;
    var $lastx=0, $lasty=0;
    var $width=0, $height=0;
    var $line_weight=1;
    var $line_style=1;	// Default line style is solid
    var $obs_list=array();
    var $font_size=12,$font_family=FF_FONT1, $font_style=FS_NORMAL;
    var $font_file='';
    var $text_halign="left",$text_valign="bottom";
    var $ttf=null;
    var $use_anti_aliasing=false;
    var $quality=null;
    var $colorstack=array(),$colorstackidx=0;
    var $canvascolor = 'white' ;
    var $langconv = null ;

    //---------------
    // CONSTRUCTOR
    function Image($aWidth,$aHeight,$aFormat=DEFAULT_GFORMAT) {
	$this->CreateImgCanvas($aWidth,$aHeight);
	$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();
    }

    // Should we use anti-aliasing. Note: This really slows down graphics!
    function SetAntiAliasing() {
	$this->use_anti_aliasing=true;
    }

    function CreateRawCanvas($aWidth=0,$aHeight=0) {
	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)");
	}
	if( @$GLOBALS['gd2']==true && USE_TRUECOLOR ) {
	    $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();
	} else {
	    $this->img = @imagecreate($aWidth, $aHeight);	
	    if( $this->img < 1 ) {
		JpGraphError::RaiseL(25126);
		//die("<b>JpGraph Error:</b> Can't create image. Check that you really have the GD library installed.");
	    }
	}
	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,$aWidth,$aHeight);

	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 = $GLOBALS['copyfunc'] ;
	}
	$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.');
		}
		if( @$GLOBALS['gd2']==true && USE_TRUECOLOR ) {
		    $tmpimg = @imagecreatetruecolor($toWidth, $toHeight);
		} else {
		    $tmpimg = @imagecreate($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);
	}
    }

    function GetWidth($aImg=null) {
	if( $aImg === null ) 
	    $aImg = $this->img;
	return imagesx($aImg);
    }

    function GetHeight($aImg=null) {
	if( $aImg === null ) 
	    $aImg = $this->img;
	return imagesy($aImg);
    }
    
    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) {
	if( $GLOBALS['gd2'] )
	    ImageAlphaBlending($this->img,$aFlg);
	else 
	    JpGraphError::RaiseL(25086);//('You only seem to have GD 1.x installed. To enable Alphablending requires GD 2.x or higher. Please install GD or make sure the constant USE_GD2 is specified correctly to reflect your installation. By default it tries to autodetect what version of GD you have installed. On some very rare occasions it may falsely detect GD2 where only GD1 is installed. You must then set USE_GD2 to false.');
    }

	
    function SetAutoMargin() {	
	GLOBAL $gJpgBrandTiming;
	$min_bm=10;
	/*
	if( $gJpgBrandTiming )
	    $min_bm=15;		
	*/
	$lm = min(40,$this->width/7);
	$rm = min(20,$this->width/10);
	$tm = max(20,$this->height/7);
	$bm = max($min_bm,$this->height/7);
	$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;
	$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') ) {
		JpGraphError::RaiseL(25087);//('This PHP build has not been configured with TTF support. You need to recompile your PHP installation with FreeType support.');
		exit();
	    }
	    $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 = 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];
	}
    }
	
    // 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
    function GetTextWidth($txt,$angle=0) {

	$tmp = 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) {

	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;
	
	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");
	$this->StrokeText($x, $y, $txt, $dir, $paragraph_align);
	$bb = array($x-$xmarg,$y+$height-$ymarg,$x+$width,$y+$height-$ymarg,
		    $x+$width,$y-$ymarg,$x-$xmarg,$y-$ymarg);
	$this->SetTextAlign($h,$v);
	return $bb;
    }

    // Set text alignment	
    function SetTextAlign($halign,$valign="bottom") {
	$this->text_halign=$halign;
	$this->text_valign=$valign;
    }
	

    function _StrokeBuiltinFont($x,$y,$txt,$dir=0,$paragraph_align="left",&$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;
	
	if( $dir==90 ) {
	    imagestringup($this->img,$this->font_family,$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( ereg("\n",$txt) ) { 
		$tmp = split("\n",$txt);
		for($i=0; $i < count($tmp); ++$i) {
		    $w1 = $this->GetTextWidth($tmp[$i]);
		    if( $paragraph_align=="left" ) {
			imagestring($this->img,$this->font_family,$x,$y-$h+1+$i*$fh,$tmp[$i],$this->current_color);
		    }
		    elseif( $paragraph_align=="right" ) {
			imagestring($this->img,$this->font_family,$x+($w-$w1),
				    $y-$h+1+$i*$fh,$tmp[$i],$this->current_color);
		    }
		    else {
			imagestring($this->img,$this->font_family,$x+$w/2-$w1/2,
				    $y-$h+1+$i*$fh,$tmp[$i],$this->current_color);
		    }
		}
	    } 
	    else {
		//Put the text
		imagestring($this->img,$this->font_family,$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 GetTTFBBox($aTxt,$aAngle=0) {
	$bbox = @ImageTTFBBox($this->font_size,$aAngle,$this->font_file,$aTxt);
	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.");
	}
	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->GetTTFBBox($aTxt,$aAngle);

	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 $box[1]-$box[7]+1;
    }

    function GetBBoxWidth($aTxt,$aAngle=0) {
	$box = $this->GetBBoxTTF($aTxt,$aAngle);
	return $box[2]-$box[0]+1;	
    }

    function _StrokeTTF($x,$y,$txt,$dir=0,$paragraph_align="left",&$aBoundingBox,$debug=false) {

	// Setupo default inter line margin for paragraphs to
	// 25% of the font height.
	$ConstLineSpacing = 0.25 ;

	// Remember the anchor point before adjustment
	if( $debug ) {
	    $ox=$x;
	    $oy=$y;
	}

	if( !ereg("\n",$txt) || ($dir>0 && ereg("\n",$txt)) ) {
	    // Format a single line

	    $txt = $this->AddTxtCR($txt);

	    $bbox=$this->GetBBoxTTF($txt,$dir);
	    
	    // Align x,y ot lower left corner of bbox
	    $x -= $bbox[0];
	    $y -= $bbox[1];

	    // Note to self: "topanchor" is deprecated after we changed the
	    // bopunding box stuff. 
	    if( $this->text_halign=="right" || $this->text_halign=="topanchor" ) 
		$x -= $bbox[2]-$bbox[0];
	    elseif( $this->text_halign=="center" ) $x -= ($bbox[2]-$bbox[0])/2; 
	    
	    if( $this->text_valign=="top" ) $y += abs($bbox[5])+$bbox[1];
	    elseif( $this->text_valign=="center" ) $y -= ($bbox[5]-$bbox[1])/2; 

	    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=@ImageTTFBBox($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
		$box=@ImageTTFBBox($this->font_size,$dir,$this->font_file,$txt);
		$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 = 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 ;
		}

		$xl -= $bbox[0];
		$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]); 

		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 >= _FF_FIRST && $this->font_family <= _FF_LAST)  {
	    $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::raise("Too 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];
    }
	
	
    // Why this duplication? Because this way we can call this method
    // for any image and not only the current objsct
    function AdjSat($sat) {	
	if( $GLOBALS['gd2'] && USE_TRUECOLOR )
	    return;
	$this->_AdjSat($this->img,$sat);	
    }	
	
    function _AdjSat($img,$sat) {
	$nbr = imagecolorstotal ($img);
	for( $i=0; $i<$nbr; ++$i ) {
	    $colarr = imagecolorsforindex ($img,$i);
	    $rgb[0]=$colarr["red"];
	    $rgb[1]=$colarr["green"];
	    $rgb[2]=$colarr["blue"];
	    $rgb = $this->AdjRGBSat($rgb,$sat);
	    imagecolorset ($img, $i, $rgb[0], $rgb[1], $rgb[2]);
	}
    }
	
    function AdjBrightContrast($bright,$contr=0) {
	if( $GLOBALS['gd2'] && USE_TRUECOLOR )
	    return;
	$this->_AdjBrightContrast($this->img,$bright,$contr);
    }

    function _AdjBrightContrast($img,$bright,$contr=0) {
	if( $bright < -1 || $bright > 1 || $contr < -1 || $contr > 1 )
	    JpGraphError::RaiseL(25099);//(" Parameters for brightness and Contrast out of range [-1,1]");		
	$nbr = imagecolorstotal ($img);
	for( $i=0; $i<$nbr; ++$i ) {
	    $colarr = imagecolorsforindex ($img,$i);
	    $r = $this->AdjRGBBrightContrast($colarr["red"],$bright,$contr);
	    $g = $this->AdjRGBBrightContrast($colarr["green"],$bright,$contr);
	    $b = $this->AdjRGBBrightContrast($colarr["blue"],$bright,$contr);		
	    imagecolorset ($img, $i, $r, $g, $b);
	}
    }
	
    // Private helper function for adj sat
    // Adjust saturation for RGB array $u. $sat is a value between -1 and 1
    // Note: Due to GD inability to handle true color the RGB values are only between
    // 8 bit. This makes saturation quite sensitive for small increases in parameter sat.
    // 
    // Tip: To get a grayscale picture set sat=-100, values <-100 changes the colors
    // to it's complement.
    // 
    // Implementation note: The saturation is implemented directly in the RGB space
    // by adjusting the perpendicular distance between the RGB point and the "grey"
    // line (1,1,1). Setting $sat>0 moves the point away from the line along the perp.
    // distance and a negative value moves the point closer to the line.
    // The values are truncated when the color point hits the bounding box along the
    // RGB axis.
    // DISCLAIMER: I'm not 100% sure this is he correct way to implement a color 
    // saturation function in RGB space. However, it looks ok and has the expected effect.
    function AdjRGBSat($rgb,$sat) {
	// TODO: Should be moved to the RGB class
	// Grey vector
	$v=array(1,1,1);

	// Dot product
	$dot = $rgb[0]*$v[0]+$rgb[1]*$v[1]+$rgb[2]*$v[2];

	// Normalize dot product
	$normdot = $dot/3;	// dot/|v|^2

	// Direction vector between $u and its projection onto $v
	for($i=0; $i<3; ++$i)
	    $r[$i] = $rgb[$i] - $normdot*$v[$i];

	// Adjustment factor so that sat==1 sets the highest RGB value to 255
	if( $sat > 0 ) {
	    $m=0;
	    for( $i=0; $i<3; ++$i) {
		if( sign($r[$i]) == 1 && $r[$i]>0)
		    $m=max($m,(255-$rgb[$i])/$r[$i]);
	    }
	    $tadj=$m;
	}
	else
	    $tadj=1;
		
	$tadj = $tadj*$sat;	
	for($i=0; $i<3; ++$i) {
	    $un[$i] = round($rgb[$i] + $tadj*$r[$i]);		
	    if( $un[$i]<0 ) $un[$i]=0;		// Truncate color when they reach 0
	    if( $un[$i]>255 ) $un[$i]=255;// Avoid potential rounding error
	}		
	return $un;	
    }	

    // Private helper function for AdjBrightContrast
    function AdjRGBBrightContrast($rgb,$bright,$contr) {
	// TODO: Should be moved to the RGB class
	// First handle contrast, i.e change the dynamic range around grey
	if( $contr <= 0 ) {
	    // Decrease contrast
	    $adj = abs($rgb-128) * (-$contr);
	    if( $rgb < 128 ) $rgb += $adj;
	    else $rgb -= $adj;
	}
	else { // $contr > 0
	    // Increase contrast
	    if( $rgb < 128 ) $rgb = $rgb - ($rgb * $contr);
	    else $rgb = $rgb + ((255-$rgb) * $contr);
	}
	
	// Add (or remove) various amount of white
	$rgb += $bright*255;	
	$rgb=min($rgb,255);
	$rgb=max($rgb,0);
	return $rgb;	
    }
	
    function SetLineWeight($weight) {
	$this->line_weight = $weight;
    }
	
    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="") {

	if( $GLOBALS['gd2'] ) {
	    while( $s < 0 ) $s += 360;
	    while( $e < 0 ) $e += 360;
	    if( $style=="" ) 
		$style=IMG_ARC_PIE;
	    imagefilledarc($this->img,round($xc),round($yc),round($w),round($h),
			   round($s),round($e),$this->current_color,$style);
	    return;
	}


	// In GD 1.x we have to do it ourself interesting enough there is surprisingly
	// little difference in time between doing it PHP and using the optimised GD 
	// library (roughly ~20%) I had expected it to be at least 100% slower doing it
	// manually with a polygon approximation in PHP.....
	$fillcolor = $this->current_color_name;

	$w /= 2; // We use radius in our calculations instead
	$h /= 2;

	// Setup the angles so we have the same conventions as the builtin
	// FilledArc() which is a little bit strange if you ask me....

	$s = 360-$s;
	$e = 360-$e;

	if( $e > $s ) {
	    $e = $e - 360;
	    $da = $s - $e; 
	}
	$da = $s-$e;

	// We use radians
	$s *= M_PI/180;
	$e *= M_PI/180;
	$da *= M_PI/180;

	// Calculate a polygon approximation
	$p[0] = $xc;
	$p[1] = $yc;

	// Heuristic on how many polygons we need to make the
	// arc look good
	$numsteps = round(8 * abs($da) * ($w+$h)*($w+$h)/1500);

	if( $numsteps == 0 ) return;
	if( $numsteps < 7 ) $numsteps=7;
	$delta = abs($da)/$numsteps;
	
	$pa=array();
	$a = $s;
	for($i=1; $i<=$numsteps; ++$i ) {
	    $p[2*$i] = round($xc + $w*cos($a));
	    $p[2*$i+1] = round($yc - $h*sin($a));
	    //$a = $s + $i*$delta; 
	    $a -= $delta; 
	    $pa[2*($i-1)] = $p[2*$i];
	    $pa[2*($i-1)+1] = $p[2*$i+1];
	}

	// Get the last point at the exact ending angle to avoid
	// any rounding errors.
	$p[2*$i] = round($xc + $w*cos($e));
	$p[2*$i+1] = round($yc - $h*sin($e));
	$pa[2*($i-1)] = $p[2*$i];
	$pa[2*($i-1)+1] = $p[2*$i+1];
	$i++;

	$p[2*$i] = $xc;
    	$p[2*$i+1] = $yc;
	if( $fillcolor != "" ) {
	    $this->PushColor($fillcolor);
	    imagefilledpolygon($this->img,$p,count($p)/2,$this->current_color);
	    $this->PopColor();
	}
    }

    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);
	$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. 
	    if( $GLOBALS['gd2'] ) {
		imagefilledarc($this->img,$xc,$yc,2*$w,2*$h,$s,$e,$this->current_color,IMG_ARC_NOFILL | IMG_ARC_EDGED ) ;
	    }
	    else {
		$this->Arc($xc,$yc,2*$w+2,2*$h+2,$s,$e);
		$xx = $w * cos(2*M_PI - $s*M_PI/180) + $xc;
		$yy = $yc - $h * sin(2*M_PI - $s*M_PI/180);
		$this->Line($xc,$yc,$xx,$yy);
		$xx = $w * cos(2*M_PI - $e*M_PI/180) + $xc;
		$yy = $yc - $h * sin(2*M_PI - $e*M_PI/180);
		$this->Line($xc,$yc,$xx,$yy);
	    }
	    $this->PopColor();
	}
    }

    function Ellipse($xc,$yc,$w,$h) {
	$this->Arc($xc,$yc,$w,$h,0,360);
    }
	
    // Breseham circle gives visually better result then using GD
    // built in arc(). It takes some more time but gives better
    // accuracy.
    function BresenhamCircle($xc,$yc,$r) {
	$d = 3-2*$r;
	$x = 0;
	$y = $r;
	while($x<=$y) {
	    $this->Point($xc+$x,$yc+$y);			
	    $this->Point($xc+$x,$yc-$y);
	    $this->Point($xc-$x,$yc+$y);
	    $this->Point($xc-$x,$yc-$y);
			
	    $this->Point($xc+$y,$yc+$x);
	    $this->Point($xc+$y,$yc-$x);
	    $this->Point($xc-$y,$yc+$x);
	    $this->Point($xc-$y,$yc-$x);
			
	    if( $d<0 ) $d += 4*$x+6;
	    else {
		$d += 4*($x-$y)+10;		
		--$y;
	    }
	    ++$x;
	}
    }
			
    function Circle($xc,$yc,$r) {
	if( USE_BRESENHAM )
	    $this->BresenhamCircle($xc,$yc,$r);
	else {

	    /*
            // Some experimental code snippet to see if we can get a decent 
	    // result doing a trig-circle
	    // Create an approximated circle with 0.05 rad resolution
	    $end = 2*M_PI;
	    $l = $r/10;
	    if( $l < 3 ) $l=3;
	    $step_size = 2*M_PI/(2*$r*M_PI/$l);
	    $pts = array();
	    $pts[] = $r + $xc;
	    $pts[] = $yc;
	    for( $a=$step_size; $a <= $end; $a += $step_size ) {
		$pts[] = round($xc + $r*cos($a));
		$pts[] = round($yc - $r*sin($a));
	    }
	    imagepolygon($this->img,$pts,count($pts)/2,$this->current_color);
	    */

	    $this->Arc($xc,$yc,$r*2,$r*2,0,360);		

	    // For some reason imageellipse() isn't in GD 2.0.1, PHP 4.1.1
	    //imageellipse($this->img,$xc,$yc,$r,$r,$this->current_color);
	}
    }
	
    function FilledCircle($xc,$yc,$r) {
	if( $GLOBALS['gd2'] ) {
	    imagefilledellipse($this->img,round($xc),round($yc),
	    		       2*$r,2*$r,$this->current_color);
	}
	else {
	    for( $i=1; $i < 2*$r; $i += 2 ) {
		// To avoid moire patterns we have to draw some
		// 1 extra "skewed" filled circles
		$this->Arc($xc,$yc,$i,$i,0,360);
		$this->Arc($xc,$yc,$i+1,$i,0,360);
		$this->Arc($xc,$yc,$i+1,$i+1,0,360);
	    }
	}	
    }
	
    // 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);
    }

    // Anti-aliased line. 
    // Note that this is roughly 8 times slower then a normal line!
    function WuLine($x1,$y1,$x2,$y2) {
	// Get foreground line color
	$lc = imagecolorsforindex($this->img,$this->current_color);
	$lc = array($lc["red"],$lc["green"],$lc["blue"]);

	$dx = $x2-$x1;
	$dy = $y2-$y1;
	
	if( abs($dx) > abs($dy) ) {
	    if( $dx<0 ) {
		$dx = -$dx;$dy = -$dy;
		$tmp=$x2;$x2=$x1;$x1=$tmp;
		$tmp=$y2;$y2=$y1;$y1=$tmp;
	    }
	    $x=$x1<<16; $y=$y1<<16;
	    $yinc = ($dy*65535)/$dx;
	    while( ($x >> 16) < $x2 ) {
				
		$bc = @imagecolorsforindex($this->img,imagecolorat($this->img,$x>>16,$y>>16));
		if( $bc <= 0 ) {
		    JpGraphError::RaiseL(25100);//('Problem with color palette and your GD setup. Please disable anti-aliasing or use GD2 with true-color. If you have GD2 library installed please make sure that you have set the USE_GD2 constant to true and that truecolor is enabled.');
		}
		$bc=array($bc["red"],$bc["green"],$bc["blue"]);
				
		$this->SetColor($this->lip($lc,$bc,($y & 0xFFFF)/65535));
		imagesetpixel($this->img,$x>>16,$y>>16,$this->current_color);
		$this->SetColor($this->lip($lc,$bc,(~$y & 0xFFFF)/65535));
		imagesetpixel($this->img,$x>>16,($y>>16)+1,$this->current_color);
		$x += 65536; $y += $yinc;
	    }
	}
	else {
	    if( $dy<0 ) {
		$dx = -$dx;$dy = -$dy;
		$tmp=$x2;$x2=$x1;$x1=$tmp;
		$tmp=$y2;$y2=$y1;$y1=$tmp;
	    }
	    $x=$x1<<16; $y=$y1<<16;
	    $xinc = ($dx*65535)/$dy;	
	    while( ($y >> 16) < $y2 ) {
				
		$bc = @imagecolorsforindex($this->img,imagecolorat($this->img,$x>>16,$y>>16));
		if( $bc <= 0 ) {
		    JpGraphError::RaiseL(25100);//('Problem with color palette and your GD setup. Please disable anti-aliasing or use GD2 with true-color. If you have GD2 library installed please make sure that you have set the USE_GD2 constant to true and truecolor is enabled.');

		}

		$bc=array($bc["red"],$bc["green"],$bc["blue"]);				
				
		$this->SetColor($this->lip($lc,$bc,($x & 0xFFFF)/65535));
		imagesetpixel($this->img,$x>>16,$y>>16,$this->current_color);
		$this->SetColor($this->lip($lc,$bc,(~$x & 0xFFFF)/65535));
		imagesetpixel($this->img,($x>>16)+1,$y>>16,$this->current_color);
		$y += 65536; $x += $xinc;
	    }
	}
	$this->SetColor($lc);
	imagesetpixel($this->img,$x2,$y2,$this->current_color);		
	imagesetpixel($this->img,$x1,$y1,$this->current_color);			
    }

    // 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");
	$this->line_style=$s;
    }
	
    // Same as Line but take the line_style into account
    function StyleLine($x1,$y1,$x2,$y2) {
	switch( $this->line_style ) {
	    case 1:// Solid
		$this->Line($x1,$y1,$x2,$y2);
		break;
	    case 2: // Dotted
		$this->DashedLine($x1,$y1,$x2,$y2,1,6);
		break;
	    case 3: // Dashed
		$this->DashedLine($x1,$y1,$x2,$y2,2,4);
		break;
	    case 4: // Longdashes
		$this->DashedLine($x1,$y1,$x2,$y2,8,6);
		break;
	    default:
		JpGraphError::RaiseL(25104,$this->line_style);//(" Unknown line style: $this->line_style ");
		break;
	}
    }

    function Line($x1,$y1,$x2,$y2) {

	$x1 = round($x1);
	$x2 = round($x2);
	$y1 = round($y1);
	$y2 = round($y2);

	if( $this->line_weight==0 ) return;
	if( $this->use_anti_aliasing ) {
	    $dx = $x2-$x1;
	    $dy = $y2-$y1</