This file is indexed.

/usr/share/tcltk/tklib0.6/plotchart/plotpriv.tcl is in tklib 0.6-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# plotpriv.tcl --
#    Facilities to draw simple plots in a dedicated canvas
#
# Note:
#    This source file contains the private functions.
#    It is the companion of "plotchart.tcl"
#

# WidthCanvas --
#    Return the width of the canvas
# Arguments:
#    w           Name of the canvas
#    useref      Use reference width if it exists
# Result:
#    Width in pixels
#
proc ::Plotchart::WidthCanvas {w {useref 1}} {
    variable scaling

    set ref $scaling($w,reference)

    if { [string match {[0-9]*} $w] } {
        set w [string range $w 2 end]
    }

    if { [info exists scaling($ref,refwidth)] && $useref } {
        set width $scaling($ref,refwidth)
    } else {
        set width [winfo width $w]

        if { $width < 10 } {
            set width [$w cget -width]
        }
    }
    incr width -[$w cget -borderwidth]

    return $width
}

# HeightCanvas --
#    Return the height of the canvas
# Arguments:
#    w           Name of the canvas
#    useref      Use reference height if it exists
# Result:
#    Height in pixels
#
proc ::Plotchart::HeightCanvas {w {useref 1}} {
    variable scaling

    set ref $scaling($w,reference)

    if { [string match {[0-9]*} $w] } {
        set w [string range $w 2 end]
    }

    if { [info exists scaling($ref,refheight)] && $useref } {
        set height $scaling($ref,refheight)
    } else {
        set height [winfo height $w]
        if { $height < 10 } {
            set height [$w cget -height]
        }
    }
    incr height -[$w cget -borderwidth]
    return $height
}

# SavePlot --
#    Save the plot/chart to a PostScript file (using default options)
# Arguments:
#    w           Name of the canvas
#    filename    Name of the file to write
#    args        Additional optional arguments as ?option value ... ...?
#                     -format name            a file format different from PostScript to save the plot into
#                     -plotregion region      define what region of the plot to save
#                                             ('bbox' saves all within the bbox, 'window' saves what is visible in the current window)
# Result:
#    None
# Side effect:
#    A (new) PostScript file or other file format
#
proc ::Plotchart::SavePlot { w filename args } {
    array set options {-format ps -plotregion window}
    array set options $args
    foreach {opt val} $args {
        if {$opt ni {-format -plotregion}} {
            return -code error "Unknown option: $opt - must be: -format or -plotregion"
        }
    }
    if {$options(-plotregion) eq "bbox" && $options(-format) ne "ps"} {
        return -code error "'-plotregion bbox' can only be used together with '-format ps'"
    }
    if {$options(-format) ne "ps"} {
        regexp {\..*} $w c
        package require Img
        #
        # This is a kludge:
        # Somehow tkwait does not always work (on Windows XP, that is)
        #
        raise [winfo toplevel $c]
        # tkwait visibility [winfo toplevel $c]
        after 2000 {set ::Plotchart::waited 0}
        vwait ::Plotchart::waited
        set img [image create photo -data $c -format window]
        $img write $filename -format $options(-format)
    } else {
        #
        # Wait for the canvas to become visible - just in case.
        # Then write the file
        #
        update idletasks
        if {$options(-plotregion) eq "window"} {
            $w postscript -file $filename
        } elseif {$options(-plotregion) eq "bbox"} {
            lassign [$w bbox all] xmin ymin xmax ymax
            # '+2' here, because the bbox from the canvas is only approximate
            # and may be a tiny bit too small sometimes, especially with text
            # at the edges
            set width  [expr {$xmax-$xmin+2}]
            set height [expr {$ymax-$ymin+2}]
            $w postscript -file $filename -x $xmin -y $ymin -height $height -width $width
        } else {
            return -code error "Unknown value '$options(-plotregion)' for -plotregion option"
        }
    }
}

# DetermineFromAxesBox --
#    Determine the layout from the information in an axes box
# Arguments:
#    axesbox           Data defining the axes box
#    pxdef             Default minimum x-coordinate
#    pydef             Default minimum y-coordinate
#    margin_right      Margin right
#    margin_bottom     Margin bottom
# Result:
#    List of four values
#
proc ::Plotchart::DetermineFromAxesBox {axesbox pxdef pydef margin_right margin_bottom} {
    variable scaling

    foreach {ref_plot dir upperx uppery axis_width axis_height} $axesbox {break}

    set pos      [string first _ $ref_plot]
    set ref_plot [string range $ref_plot [expr {$pos+1}] end]

    set refxmin $scaling($ref_plot,pxmin)
    set refymin $scaling($ref_plot,pymin)
    set refxmax $scaling($ref_plot,pxmax)
    set refymax $scaling($ref_plot,pymax)

    switch -- [string toupper $dir] {
        "N" {
            set pxmin [expr {($refxmin + $refxmax)/2}]
            set pymin $refymin
        }
        "NW" {
            set pxmin $refxmin
            set pymin $refymin
        }
        "NE" {
            set pxmin $refxmax
            set pymin $refymin
        }
        "E" {
            set pxmin $refxmax
            set pymin [expr {($refymin + $refymax)/2}]
        }
        "SE" {
            set pxmin $refxmax
            set pymin $refymax
        }
        "S" {
            set pxmin [expr {($refxmin + $refxmax)/2}]
            set pymin $refymax
        }
        "SW" {
            set pxmin $refxmin
            set pymin $refymax
        }
        "W" {
            set pxmin $refxmin
            set pymin [expr {($refymin + $refymax)/2}]
        }
        "C" {
            set pxmin [expr {($refxmin + $refxmax)/2}]
            set pymin [expr {($refymin + $refymax)/2}]
        }
        default {
            set pxmin $refxmin
            set pymin $refymin
        }
    }
    set pxmin  [expr {$pxmin       - $pxdef + $upperx}]
    set pymin  [expr {$pymin       - $pydef - $uppery}]        ;# Because of inversion of y-axis
    set width  [expr {$axis_width  + $pxdef + $margin_right}]
    set height [expr {$axis_height + $pydef + $margin_bottom}]

    return [list $pxmin $pymin $width $height]
}

# MarginsRectangle --
#    Determine the margins for a rectangular plot/chart
# Arguments:
#    w           Name of the plot
#    argv        List of options
#    notext      Number of lines of text to make room for at the top
#                (default: 2.0)
#    text_width  Number of characters to be displayed at most on left
#                (default: 8)
# Result:
#    List of four values
#
proc ::Plotchart::MarginsRectangle { w argv {notext 2.0} {text_width 8}} {
    variable config
    variable scaling

    if { [string match {[0-9]*} $w] } {
        set c [string range $w 2 end]
    } else {
        set c $w
    }
    set char_width  $config(font,char_width)
    set char_height $config(font,char_height)
    set config($w,font,char_width)  $char_width
    set config($w,font,char_height) $char_height

    foreach {char_width char_height} [FontMetrics $w] {break}
    set margin_right [expr {$char_width * 4}]
    if { $margin_right < $config($w,margin,right) } {
        set margin_right $config($w,margin,right)
    }
    if { $config($w,rightaxis,usevsubtext) } {
        set char_height [font metrics $config($w,rightaxis,vsubtextfont) -linespace]
        set margin_right [expr {$margin_right + $char_height + 4}]
    }
    set margin_bottom [expr {$char_height * 2 + 2}]
    if { $margin_bottom < $config($w,margin,bottom) } {
        set margin_bottom $config($w,margin,bottom)
    }
    if { $config($w,bottomaxis,usesubtext) } {
        set char_height [font metrics $config($w,bottomaxis,subtextfont) -linespace]
        set margin_bottom [expr {$margin_bottom + $char_height}]
    }

    set pxmin [expr {$char_width*$text_width}]
    if { $pxmin < $config($w,margin,left) } {
        set pxmin $config($w,margin,left)
    }
    set pymin [expr {int($char_height*$notext) + [$w cget -borderwidth]}]
    if { $pymin < $config($w,margin,top) } {
        set pymin $config($w,margin,top)
    }
    if { $config($w,leftaxis,usesubtext) || $config($w,rightaxis,usesubtext) } {
        set char_height1 [font metrics $config($w,leftaxis,subtextfont) -linespace]
        set char_height2 [font metrics $config($w,rightaxis,subtextfont) -linespace]
        set pymin [expr {$pymin + max($char_height1,$char_height2)}]
    }
    if { $config($w,leftaxis,usevsubtext) } {
        set char_height [font metrics $config($w,leftaxis,vsubtextfont) -linespace]
        set pxmin [expr {$pxmin + $char_height + 4}]
    }

    array set options $argv
    if {[info exists options(-box)]} {
        foreach {offx offy width height} $options(-box) {break}
        if { $offy == 0 } {
            set offy [$w cget -borderwidth]
        }
        set scaling($w,reference) $w
        set scaling($w,refx)      $offx
        set scaling($w,refy)      $offy
        set scaling($w,refwidth)  [expr {$offx + $width}]
        set scaling($w,refheight) [expr {$offy + $height}]
    } elseif {[info exists options(-axesbox)]} {
        foreach {offx offy width height} [DetermineFromAxesBox $options(-axesbox) $pxmin $pymin $margin_right $margin_bottom] {break}
        if { $offy == 0 } {
            set offy [$w cget -borderwidth]
        }
        set ref_plot [lindex $options(-axesbox) 0]
        set pos      [string first _ $ref_plot]
        set ref      [string range $ref_plot [expr {$pos+1}] end]
        set scaling($w,reference) $scaling($ref,reference) ;# A chain of references is possible!
    } else {
        set scaling($w,reference) $w
        set offx   0
        set offy   [$w cget -borderwidth]
        set width  [WidthCanvas $w]
        set height [HeightCanvas $w]
        set scaling($w,refx)      0
        set scaling($w,refy)      0
        set scaling($w,refwidth)  $width
        set scaling($w,refheight) $height
    }

    set pxmin [expr {$offx + $pxmin}]
    set pymin [expr {$offy + $pymin}]

    set pxmax [expr {$offx + $width  - $margin_right}]
    set pymax [expr {$offy + $height - $margin_bottom}]

    set ref $scaling($w,reference)

    if { ! [info exists scaling($ref,boxxmin)] } {
        set scaling($ref,boxxmin) $pxmin
        set scaling($ref,boxymin) $pymin
        set scaling($ref,boxxmax) $pxmax
        set scaling($ref,boxymax) $pymax
        set scaling($ref,refx)    $offx
        set scaling($ref,refy)    $offy
    } else {
        Minset scaling($ref,boxxmin) $pxmin
        Minset scaling($ref,boxymin) $pymin
        Maxset scaling($ref,boxxmax) $pxmax
        Maxset scaling($ref,boxymax) $pymax
        Minset scaling($ref,refx)    $offx
        Minset scaling($ref,refy)    $offy
    }

    return [list $pxmin $pymin $pxmax $pymax]
}

# Minset, Maxset --
#     Auxiliary procedures to conditionally update a variable
# Arguments:
#     varName    Name of the variable
#     newValue   New value
#
proc ::Plotchart::Minset {varName newValue} {
    upvar 1 $varName var

    if { $var > $newValue } {
        set var $newValue
    }
}
proc ::Plotchart::Maxset {varName newValue} {
    upvar 1 $varName var

    if { $var < $newValue } {
        set var $newValue
    }
}

# MarginsSquare --
#    Determine the margins for a square plot/chart
# Arguments:
#    w           Name of the canvas
#    notext      Number of lines of text to make room for at the top
#                (default: 2.0)
#    text_width  Number of characters to be displayed at most on left
#                (default: 8)
# Result:
#    List of four values
#
proc ::Plotchart::MarginsSquare { w {notext 2.0} {text_width 8}} {
    variable config
    variable scaling

    set scaling($w,reference) $w
    set scaling($w,refx)      0
    set scaling($w,refy)      [$w cget -borderwidth]
    set scaling($w,refwidth)  [WidthCanvas $w]
    set scaling($w,refheight) [HeightCanvas $w]

    set char_width  $config(font,char_width)
    set char_height $config(font,char_height)
    set config($w,font,char_width)  $char_width
    set config($w,font,char_height) $char_height

    foreach {char_width char_height} [FontMetrics $w] {break}
    set margin_right [expr {$char_width * 4}]
    if { $margin_right < $config($w,margin,right) } {
        set margin_right $config($w,margin,right)
    }
    set margin_bottom [expr {$char_height * 2 + 2}]
    if { $margin_bottom < $config($w,margin,bottom) } {
        set margin_bottom $config($w,margin,bottom)
    }

    set pxmin [expr {$char_width*$text_width}]
    if { $pxmin < $config($w,margin,left) } {
        set pxmin $config($w,margin,left)
    }
    set pymin [expr {int($char_height*$notext)}]
    if { $pymin < $config($w,margin,top) } {
        set pymin $config($w,margin,top)
    }
    set pxmax [expr {[WidthCanvas $w]  - $margin_right}]
    set pymax [expr {[HeightCanvas $w] - $margin_bottom}]

    if { $pxmax-$pxmin > $pymax-$pymin } {
        set pxmax [expr {$pxmin + ($pymax - $pymin)}]
    } else {
        set pymax [expr {$pymin + ($pxmax - $pxmin)}]
    }

    return [list $pxmin $pymin $pxmax $pymax]
}

# MarginsCircle --
#    Determine the margins for a circular plot/chart
# Arguments:
#    w           Name of the canvas
#    args        additional arguments for placement of plot,
#                currently: '-box', '-reference', and '-units'
# Result:
#    List of four values giving the pixel coordinates
#    of the boundary of the piechart
#
proc ::Plotchart::MarginsCircle { w args } {
   variable scaling

   array set options $args
   if { [info exists options(-box)] } {
       set scaling($w,reference) $w
   } elseif { [info exists options(-reference)] } {
       set ref_plot [lindex $options(-reference) 0]
       set pos      [string first _ $ref_plot]
       set ref      [string range $ref_plot [expr {$pos+1}] end]
       set scaling($w,reference) $scaling($ref,reference)
   } else {
       set scaling($w,reference) $w
   }

   set pxmin 80
   set pymin 30
   set pxmax [expr {[WidthCanvas $w]  - 80}]
   set pymax [expr {[HeightCanvas $w] - 30}]
   #set pxmax [expr {[$w cget -width]  - 80}]
   #set pymax [expr {[$w cget -height] - 30}]

   # width (dx) and height (dy) of plot region in pixels:
   if {[info exists options(-units)]} {
      # refUnitX, refUnitY - size of one world coordinate unit in the piechart,
      #      given as canvas coords (can also be m,c,i,p units)
      # Note: the pie is always 2 world coordinate units in diameter
      #
      lassign $options(-units) refUnitX refUnitY
      set wc [string range $w 2 end]
      set refUnitX [winfo pixels $wc $refUnitX]
      set refUnitY [winfo pixels $wc $refUnitY]
      set dx [expr {$refUnitX * 2}]
      set dy [expr {$refUnitY * 2}]
   } else {
      set dx [expr {$pxmax-$pxmin+1}]
      set dy [expr {$pymax-$pymin+1}]
      # make sure, we get a centred circle:
      if {$dx < $dy} {
          set dy $dx
      } else {
          set dx $dy
      }
      set pxmin [expr {($pxmin+$pxmax-$dx)/2}]
   }

   # new default coords of plotting region:
   set pxmax [expr {$pxmin + $dx}]
   set pymax [expr {$pymin + $dy}]

   if {[info exists options(-reference)]} {
        # refPlot - name of the plot referring to
        # refX - x world coordinate of center of new piechart in refPlot coordinate system
        # refY - see above, just for y
        #
        lassign $options(-reference) refPlot refX refY
        set pos [string first _ $refPlot]
        set refPlot [string range $refPlot [expr {$pos+1}] end]
        lassign [coordsToPixel $refPlot $refX $refY] refpx refpy
        if {$dx < $dy} {set delta [expr {$dx/2.0}]} else {set delta [expr {$dy/2.0}]}
        set pxmin [expr {$refpx - $delta}]
        set pxmax [expr {$refpx + $delta}]
        set pymin [expr {$refpy - $delta}]
        set pymax [expr {$refpy + $delta}]
   } elseif {[info exists options(-box)]} {
        # put the pie into the middle of the -box and make it
        # as large as possible, ignoring the labels for now,
        # that may be placed outside the box
        # Note: also ignores -units setting
        lassign $options(-box) pxmin pymin width height
        if {$height >= $width} {
            # place vertically in the middle of the -box
            if { $pxmin == 0 } {set pxmin [$w cget -borderwidth]}
            set pymin [expr {$pymin + ($height-$width)/2.0}]
            if { $pymin == 0 } {set pymin [$w cget -borderwidth]}
        } else {
            # place horizontally in the middle of the -box
            if { $pymin == 0 } {set pymin [$w cget -borderwidth]}
            set pxmin [expr {$pxmin + ($width-$height)/2.0}]
            if { $pxmin == 0 } {set pxmin [$w cget -borderwidth]}
        }
        # only take the smallest dimension to keep the pie a circle:
        if {$width < $height} {set height $width}
        if {$height < $width} {set width $height}
        set pxmax [expr {$pxmin + $width}]
        set pymax [expr {$pymin + $height}]

        set scaling($w,refx)      $pxmin
        set scaling($w,refy)      $pymin
        set scaling($w,refwidth)  [expr {$pxmin + $width}]
        set scaling($w,refheight) [expr {$pymin + $height}]
   } else {
        set scaling($w,refx)      0
        set scaling($w,refy)      [$w cget -borderwidth]
        set scaling($w,refwidth)  [WidthCanvas $w]
        set scaling($w,refheight) [HeightCanvas $w]
   }

   return [list $pxmin $pymin $pxmax $pymax]
}

# Margins3DPlot --
#    Determine the margins for a 3D plot
# Arguments:
#    w           Name of the canvas
# Result:
#    List of four values
#
proc ::Plotchart::Margins3DPlot { w } {
   variable scaling

   set scaling($w,reference) $w
   set scaling($w,refx)      0
   set scaling($w,refy)      [$w cget -borderwidth]
   set scaling($w,refwidth)  [WidthCanvas $w]
   set scaling($w,refheight) [HeightCanvas $w]

   set yfract 0.33
   set zfract 0.50
   if { [info exists scaling($w,yfract)] } {
      set yfract $scaling($w,yfract)
   } else {
      set scaling($w,yfract) $yfract
   }
   if { [info exists scaling($w,zfract)] } {
      set zfract $scaling($w,zfract)
   } else {
      set scaling($w,zfract) $zfract
   }

   set yzwidth  [expr {(-120+[WidthCanvas $w])/(1.0+$yfract)}]
   set yzheight [expr {(-60+[HeightCanvas $w])/(1.0+$zfract)}]
   #set yzwidth  [expr {(-120+[$w cget -width])/(1.0+$yfract)}]
   #set yzheight [expr {(-60+[$w cget -height])/(1.0+$zfract)}]

   set pxmin    [expr {60+$yfract*$yzwidth}]
   set pxmax    [expr {[WidthCanvas $w] - 60}]
   #set pxmax    [expr {[$w cget -width] - 60}]
   set pymin    30
   set pymax    [expr {30+$yzheight}]

   return [list $pxmin $pymin $pxmax $pymax]
}

# GetPlotArea --
#    Return the area reserved for the plot
# Arguments:
#    w           Name of the canvas
# Result:
#    List of: (x,y) upper left, (x,y) lower right, width and height
#
proc ::Plotchart::GetPlotArea { w } {
   variable scaling

   set width  [expr {$scaling($w,pxmax) - $scaling($w,pxmin) + 1}]
   set height [expr {$scaling($w,pymax) - $scaling($w,pymin) + 1}]

   return [list $scaling($w,pxmin) $scaling($w,pymin) $scaling($w,pxmax) $scaling($w,pymax) $width $height]
}

# CopyScalingData --
#    Copy the scaling data for coordsToPixel and friends if needed
# Arguments:
#    w           Name of the plot
#    c           Name of the canvas
# Result:
#    None
#
proc ::Plotchart::CopyScalingData { w c } {
   variable scaling

   if { [string match "00*" $w] } {
       foreach var {new xmin xmax ymin ymax pxmin pxmax pymin pymax coordSystem xfactor yfactor} {
           set scaling($c,$var) $scaling($w,$var)
       }
   }
}

# SetColours --
#    Set the colours for those plots that treat them as a global resource
# Arguments:
#    w           Name of the canvas
#    args        List of colours to be used
# Result:
#    None
#
proc ::Plotchart::SetColours { w args } {
   variable scaling

   set scaling($w,colours) $args
}

# CycleColours --
#    create cycling colours for those plots that treat them as a global resource
# Arguments:
#    colours     List of colours to be used. An empty list will activate to default colours
#    nr_data     Number of data records
# Result:
#    List of 'nr_data' colours to be used
#
proc ::Plotchart::CycleColours { colours nr_data } {
   if {![llength ${colours}]} {
       # force to most usable default colour list
       set colours {green blue red cyan yellow magenta}
   }

   if {[llength ${colours}] < ${nr_data}} {
   # cycle through colours
   set init_colours ${colours}
        set colours {}
        set pos 0
        for {set nr 0} {${nr} < ${nr_data}} {incr nr} {
            lappend colours [lindex ${init_colours} ${pos}]
            incr pos
            if {[llength ${init_colours}] <= ${pos}} {
                set pos 0
            }
   }
        if {[string equal [lindex ${colours} 0] [lindex ${colours} end]]} {
            # keep first and last colour different from selected colours
       #    this will /sometimes fail in cases with only one/two colours in list
       set colours [lreplace ${colours} end end [lindex ${colours} 1]]
        }
   }
   return ${colours}
}

# DataConfig --
#    Configure the data series
# Arguments:
#    w           Name of the canvas
#    series      Name of the series in question
#    args        Option and value pairs
# Result:
#    None
#
proc ::Plotchart::DataConfig { w series args } {
   variable data_series
   variable options
   variable option_keys
   variable option_values

   foreach {option value} $args {
      set idx [lsearch $options $option]
      if { $idx < 0 } {
         return -code error "Unknown or invalid option: $option (value: $value)"
      } else {
         set key [lindex $option_keys    $idx]
         set idx [lsearch $option_values $key]
         set values  [lindex $option_values [incr idx]]
         if { $values != "..." } {
            if { [lsearch $values $value] < 0 } {
               return -code error "Unknown or invalid value: $value for option $option - $values"
            }
         }
         set data_series($w,$series,$key) $value
      }
   }
}

# ScaleIsometric --
#    Determine the scaling for an isometric plot
# Arguments:
#    w           Name of the canvas
#    xmin        Minimum x coordinate
#    ymin        Minimum y coordinate
#    xmax        Maximum x coordinate
#    ymax        Maximum y coordinate
#                (default: 1.5)
# Result:
#    None
# Side effect:
#    Array with scaling parameters set
#
proc ::Plotchart::ScaleIsometric { w xmin ymin xmax ymax } {
   variable scaling

   set pxmin $scaling($w,pxmin)
   set pymin $scaling($w,pymin)
   set pxmax $scaling($w,pxmax)
   set pymax $scaling($w,pymax)

   set dx [expr {double($xmax-$xmin)/($pxmax-$pxmin)}]
   set dy [expr {double($ymax-$ymin)/($pymax-$pymin)}]

   #
   # Which coordinate is dominant?
   #
   if { $dy < $dx } {
      set yminn [expr {0.5*($ymax+$ymin) - 0.5 * $dx * ($pymax-$pymin)}]
      set ymaxn [expr {0.5*($ymax+$ymin) + 0.5 * $dx * ($pymax-$pymin)}]
      set ymin  $yminn
      set ymax  $ymaxn
   } else {
      set xminn [expr {0.5*($xmax+$xmin) - 0.5 * $dy * ($pxmax-$pxmin)}]
      set xmaxn [expr {0.5*($xmax+$xmin) + 0.5 * $dy * ($pxmax-$pxmin)}]
      set xmin  $xminn
      set xmax  $xmaxn
   }

   worldCoordinates $w $xmin $ymin $xmax $ymax
}

# PlotHandler --
#    Handle the subcommands for an XY plot or chart
# Arguments:
#    type        Type of plot/chart
#    w           Name of the canvas
#    command     Subcommand or method to run
#    args        Data for the command
# Result:
#    Whatever returned by the subcommand
#
proc ::Plotchart::PlotHandler { type w command args } {
    variable methodProc

    if { [info exists methodProc($type,$command)] } {
        if { [llength $methodProc($type,$command)] == 1 } {
            eval $methodProc($type,$command) $w $args
        } else {
            eval $methodProc($type,$command)_$w $w $args
        }
    } else {
        return -code error "No such method - $command"
    }
}

# DrawMask --
#    Draw the stuff that masks the data lines outside the graph
# Arguments:
#    w           Name of the canvas
# Result:
#    None
# Side effects:
#    Several polygons drawn in the background colour
#
proc ::Plotchart::DrawMask { w } {
    variable scaling
    variable config

    if { $config($w,mask,draw) == 0 } {
        return
    }

    if { [string match {[0-9]*} $w] } {
        set c [string range $w 2 end]
    } else {
        set c $w
    }

    set ref $scaling($w,reference)

    if { [info exists scaling($ref,boxxmin)] } {
        set pxmin  $scaling($ref,boxxmin)
        set pymin  $scaling($ref,boxymin)
        set pxmax  $scaling($ref,boxxmax)
        set pymax  $scaling($ref,boxymax)
        set offx   $scaling($ref,refx)
        set offy   $scaling($ref,refy)
    } else {
        set pxmin  [expr {$scaling($w,pxmin)-1}]
        set pymin  [expr {$scaling($w,pymin)-1}]
        set pxmax  $scaling($w,pxmax)
        set pymax  $scaling($w,pymax)
        set offx   0
        set offy   0
    }
    #set width  [expr {[WidthCanvas  $w 0] + 1}]
    #set height [expr {[HeightCanvas $w 0] + 1}]
    set width  [expr {$pxmax + $config($w,margin,right)}]
    set height [expr {$pymax + $config($w,margin,bottom)}]

    set colour $config($w,background,outercolor)

    #$w delete "mask && $w"
    $w delete "mask && $ref"
    $w create rectangle $offx  $offy  $pxmin $height -fill $colour -outline $colour -tag [list mask $ref]
    $w create rectangle $offx  $offy  $width $pymin  -fill $colour -outline $colour -tag [list mask $ref]
    $w create rectangle $offx  $pymax $width $height -fill $colour -outline $colour -tag [list mask $ref]
    $w create rectangle $pxmax $offy  $width $height -fill $colour -outline $colour -tag [list mask $ref]

    $w lower mask
}

# DrawScrollMask --
#    Draw the masking rectangles for a time or Gantt chart
# Arguments:
#    w           Name of the canvas
# Result:
#    None
# Side effects:
#    Several polygons drawn in the background colour, with appropriate
#    tags
#
proc ::Plotchart::DrawScrollMask { w } {
   variable scaling
   variable config

   set width  [expr {[WidthCanvas $w]  + 1}]
   set height [expr {[HeightCanvas $w] + 1}]
   set colour $config($w,background,outercolor)
   set pxmin  [expr {$scaling($w,pxmin)-1}]
   set pxmax  $scaling($w,pxmax)
   set pymin  [expr {$scaling($w,pymin)-1}]
   set pymax  $scaling($w,pymax)
   $w create rectangle 0      0      $pxmin $height -fill $colour -outline $colour -tag vertmask
   $w create rectangle 0      0      $width $pymin  -fill $colour -outline $colour -tag horizmask
   $w create rectangle 0      $pymax $width $height -fill $colour -outline $colour -tag horizmask
   $w create rectangle $pxmax 0      $width $height -fill $colour -outline $colour -tag vertmask

   $w create rectangle 0      0      $pxmin $pymin  -fill $colour -outline $colour -tag {topmask top}
   $w create rectangle $pxmax 0      $width $pymin  -fill $colour -outline $colour -tag {topmask top}

   $w lower topmask
   $w lower horizmask
   $w lower vertmask
}

# DrawTitle --
#    Draw the title
# Arguments:
#    w           Name of the canvas
#    title       Title to appear above the graph
#    position    Position of the title (default: center)
# Result:
#    None
# Side effects:
#    Text string drawn
#
proc ::Plotchart::DrawTitle { w title {position center}} {
    variable scaling
    variable config

    set ref    $scaling($w,reference)
    set offx   $scaling($ref,refx)
    set offy   $scaling($ref,refy)
    set width  [WidthCanvas $w]
    #set width  [$w cget -width]
    set pymin  $scaling($w,pymin)

    switch -- $position {
        "left" {
            set tx [expr {$offx + 3}]
            set anchor nw
        }
        "right" {
            set tx [expr {$width - 3}]
            set anchor ne
        }
        default {
            set tx [expr {($offx + $width)/2}]
            set anchor n
        }
    }

    $w delete "title_$anchor && $ref"
    set obj [$w create text $tx [expr {$offy + 3 + [$w cget -borderwidth]}] -text $title \
                -tags [list title title_$anchor $ref] -font $config($w,title,font) \
                -fill $config($w,title,textcolor) -anchor $anchor]

    set titlecolour $config($w,title,background)
    if { $titlecolour == "" } {
        set titlecolour $config($w,background,outercolor)
    }
    set bbox    [$w bbox $obj]
    set theight [lindex $bbox end]
    set bgobj [$w create rectangle $offx $offy $width $theight -fill $titlecolour -tag [list titlebackground $ref] -outline $titlecolour]
    $w raise titlebackground
    $w raise title
    $w raise ytext
}

# DrawSubtitle --
#    Draw the subtitle
# Arguments:
#    w           Name of the canvas
#    title       Title to appear above the graph
# Result:
#    None
# Side effects:
#    Text string drawn
#
proc ::Plotchart::DrawSubtitle { w title } {
    variable scaling
    variable config

    set ref    $scaling($w,reference)
    set offx   $scaling($ref,refx)
    set width  [WidthCanvas $w]
    set pymin  $scaling($w,pymin)

    set tx [expr {($offx + $width)/2}]
    set offy   [lindex [$w bbox title] end]
    if { $offy == {} } {
        set $scaling($ref,refy)
    }

    $w delete "subtitle && $ref"
    set obj [$w create text $tx [expr {$offy + 3 + [$w cget -borderwidth]}] -text $title \
                -tags [list subtitle $ref] -font $config($w,subtitle,font) \
                -fill $config($w,subtitle,textcolor) -anchor n]

    set titlecolour $config($w,subtitle,background)
    if { $titlecolour == "" } {
        set titlecolour $config($w,background,outercolor)
    }
    set bbox    [$w bbox $obj]
    set theight [lindex $bbox end]
    set bgobj [$w create rectangle $offx $offy $width $theight -fill $titlecolour -tag [list subtitlebackground $ref] -outline $titlecolour]
    $w raise subtitlebackground
    $w raise subtitle
    $w raise ytext
}

# DrawData --
#    Draw the data in an XY-plot
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    xcrd        Next x coordinate
#    ycrd        Next y coordinate
# Result:
#    None
# Side effects:
#    New data drawn in canvas
#
proc ::Plotchart::DrawData { w series xcrd ycrd } {
   variable data_series
   variable scaling

   #
   # Check for missing values
   #
   if { $xcrd == "" || $ycrd == "" } {
       unset -nocomplain data_series($w,$series,x)
       return
   }

   #
   # Draw the line piece
   #
   set colour "black"
   if { [info exists data_series($w,$series,-colour)] } {
      set colour $data_series($w,$series,-colour)
   }

   set type "line"
   if { [info exists data_series($w,$series,-type)] } {
      set type $data_series($w,$series,-type)
   }
   set filled "no"
   if { [info exists data_series($w,$series,-filled)] } {
      set filled $data_series($w,$series,-filled)
   }
   set fillcolour white
   if { [info exists data_series($w,$series,-fillcolour)] } {
      set fillcolour $data_series($w,$series,-fillcolour)
   }
   set width 1
   if { [info exists data_series($w,$series,-width)] } {
      set width $data_series($w,$series,-width)
   }

   foreach {pxcrd pycrd} [coordsToPixel $w $xcrd $ycrd] {break}

   if { [info exists data_series($w,$series,x)] } {
       set xold $data_series($w,$series,x)
       set yold $data_series($w,$series,y)
       foreach {pxold pyold} [coordsToPixel $w $xold $yold] {break}

       if { $filled ne "no" } {
           if { $filled eq "down" } {
               set pym $scaling($w,pymax)
           } else {
               set pym $scaling($w,pymin)
           }
           $w create polygon $pxold $pym $pxold $pyold $pxcrd $pycrd $pxcrd $pym \
               -fill $fillcolour -outline {} -width $width -tag [list data data_$series]
       }

       if { $type == "line" || $type == "both" } {
          $w create line $pxold $pyold $pxcrd $pycrd \
                         -fill $colour -width $width -tag [list data data_$series]
       }
   }

   if { $type == "symbol" || $type == "both" } {
      set symbol "dot"
      if { [info exists data_series($w,$series,-symbol)] } {
         set symbol $data_series($w,$series,-symbol)
      }
      DrawSymbolPixel $w $series $pxcrd $pycrd $symbol $colour [list "data" data_$series]
   }

   $w lower data

   set data_series($w,$series,x) $xcrd
   set data_series($w,$series,y) $ycrd
}

# DrawStripData --
#    Draw the data in a stripchart
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    xcrd        Next x coordinate
#    ycrd        Next y coordinate
# Result:
#    None
# Side effects:
#    New data drawn in canvas
#
proc ::Plotchart::DrawStripData { w series xcrd ycrd } {
   variable data_series
   variable scaling

   #
   # Check for missing values
   #
   if { $xcrd == "" || $ycrd == "" } {
       unset data_series($w,$series,x)
       return
   }

   if { $xcrd > $scaling($w,xmax) } {
      set xdelt $scaling($w,xdelt)
      set xmin  $scaling($w,xmin)
      set xmax  $scaling($w,xmax)

      set xminorg $xmin
      while { $xmax < $xcrd } {
         set xmin [expr {$xmin+$xdelt}]
         set xmax [expr {$xmax+$xdelt}]
      }
      set ymin  $scaling($w,ymin)
      set ymax  $scaling($w,ymax)

      worldCoordinates $w $xmin $ymin $xmax $ymax
      DrawXaxis $w $xmin $xmax $xdelt

      foreach {pxminorg pyminorg} [coordsToPixel $w $xminorg $ymin] {break}
      foreach {pxmin pymin}       [coordsToPixel $w $xmin    $ymin] {break}
      $w move data [expr {$pxminorg-$pxmin+1}] 0
   }

   DrawData $w $series $xcrd $ycrd
}

# DrawLogYData --
#    Draw the data in an X-logY-plot
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    xcrd        Next x coordinate
#    ycrd        Next y coordinate
# Result:
#    None
# Side effects:
#    New data drawn in canvas
#
proc ::Plotchart::DrawLogYData { w series xcrd ycrd } {

    DrawData $w $series $xcrd [expr {log10($ycrd)}]
}

# DrawLogXData --
#    Draw the data in an logX-Y-plot
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    xcrd        Next x coordinate
#    ycrd        Next y coordinate
# Result:
#    None
# Side effects:
#    New data drawn in canvas
#
proc ::Plotchart::DrawLogXData { w series xcrd ycrd } {

    DrawData $w $series [expr {log10($xcrd)}] $ycrd
}

# DrawLogXLogYData --
#    Draw the data in an logX-logY-plot
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    xcrd        Next x coordinate
#    ycrd        Next y coordinate
# Result:
#    None
# Side effects:
#    New data drawn in canvas
#
proc ::Plotchart::DrawLogXLogYData { w series xcrd ycrd } {

    DrawData $w $series [expr {log10($xcrd)}] [expr {log10($ycrd)}]
}

# DrawInterval --
#    Draw the data as an error interval in an XY-plot
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    xcrd        X coordinate
#    ymin        Minimum y coordinate
#    ymax        Maximum y coordinate
#    ycentr      Central y coordinate (optional)
# Result:
#    None
# Side effects:
#    New interval drawn in canvas
#
proc ::Plotchart::DrawInterval { w series xcrd ymin ymax {ycentr {}} } {
   variable data_series
   variable scaling

   #
   # Check for missing values
   #
   if { $xcrd == "" || $ymin == "" || $ymax == "" } {
       return
   }

   #
   # Draw the line piece
   #
   set colour "black"
   if { [info exists data_series($w,$series,-colour)] } {
      set colour $data_series($w,$series,-colour)
   }

   foreach {pxcrd pymin} [coordsToPixel $w $xcrd $ymin] {break}
   foreach {pxcrd pymax} [coordsToPixel $w $xcrd $ymax] {break}
   if { $ycentr != "" } {
       foreach {pxcrd pycentr} [coordsToPixel $w $xcrd $ycentr] {break}
   }

   #
   # Draw the I-shape (note the asymmetry!)
   #
   $w create line $pxcrd $pymin $pxcrd $pymax \
                        -fill $colour -tag [list data data_$series]
   $w create line [expr {$pxcrd-3}] $pymin [expr {$pxcrd+4}] $pymin \
                        -fill $colour -tag [list data data_$series]
   $w create line [expr {$pxcrd-3}] $pymax [expr {$pxcrd+4}] $pymax \
                        -fill $colour -tag [list data data_$series]

   if { $ycentr != "" } {
      set symbol "dot"
      if { [info exists data_series($w,$series,-symbol)] } {
         set symbol $data_series($w,$series,-symbol)
      }
      DrawSymbolPixel $w $series $pxcrd $pycentr $symbol $colour [list data data_$series]
   }

   $w lower data
}

# DrawSymbolPixel --
#    Draw a symbol in an xy-plot, polar plot or stripchart
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    pxcrd       Next x (pixel) coordinate
#    pycrd       Next y (pixel) coordinate
#    symbol      What symbol to draw
#    colour      What colour to use
#    tag         What tag to use
# Result:
#    None
# Side effects:
#    New symbol drawn in canvas
#
proc ::Plotchart::DrawSymbolPixel { w series pxcrd pycrd symbol colour tag } {
   variable data_series
   variable scaling

   set radius 4
   if { [info exists data_series($w,$series,-radius)] } {
      set radius $data_series($w,$series,-radius)
   }

   set pxmin  [expr {$pxcrd - $radius}]
   set pxmax  [expr {$pxcrd + $radius}]
   set pymin  [expr {$pycrd - $radius}]
   set pymax  [expr {$pycrd + $radius}]

   switch -- $symbol {
   "plus"     { $w create line $pxmin $pycrd $pxmax $pycrd \
                               $pxcrd $pycrd $pxcrd $pymin \
                               $pxcrd $pymax \
                               -fill $colour -tag $tag \
                               -capstyle projecting
              }
   "cross"    { $w create line $pxmin $pymin $pxmax $pymax \
                               $pxcrd $pycrd $pxmax $pymin \
                               $pxmin $pymax \
                               -fill $colour -tag $tag \
                               -capstyle projecting
              }
   "circle"   { $w create oval $pxmin $pymin $pxmax $pymax \
                               -outline $colour -tag $tag
              }
   "dot"      { $w create oval $pxmin $pymin $pxmax $pymax \
                               -outline $colour -fill $colour -tag $tag
              }
   "up"       { $w create polygon $pxmin $pymax $pxmax $pymax \
                               $pxcrd $pymin \
                               -outline $colour -fill {} -tag $tag
              }
   "upfilled" { $w create polygon $pxmin $pymax $pxmax $pymax \
                              $pxcrd $pymin \
                              -outline $colour -fill $colour -tag $tag
              }
   "down"     { $w create polygon $pxmin $pymin $pxmax $pymin \
                              $pxcrd $pymax \
                              -outline $colour -fill {} -tag $tag
              }
   "downfilled" { $w create polygon $pxmin $pymin $pxmax $pymin \
                              $pxcrd $pymax \
                              -outline $colour -fill $colour -tag $tag
              }
   }
}

# DrawTimeData --
#    Draw the data in an TX-plot
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    time        Next date/time value
#    xcrd        Next x coordinate (vertical axis)
# Result:
#    None
# Side effects:
#    New data drawn in canvas
#
proc ::Plotchart::DrawTimeData { w series time xcrd } {
    DrawData $w $series [clock scan $time] $xcrd
}

# DetermineMedian --
#    Determine the median of a sorted list of values
# Arguments:
#    values      Sorted values
# Result:
#    Median value
#
proc ::Plotchart::DetermineMedian { values } {
    set length [llength $values]

    if { $length == 1 } {
        set median [lindex $values 0]
    } elseif { $length % 2 == 1 } {
        set median [lindex $values [expr {$length/2}]]
    } else {
        set median1 [lindex $values [expr {$length/2-1}]]
        set median2 [lindex $values [expr {$length/2}]]
        set median  [expr {($median1 + $median2)/2.0}]
    }
    return $median
}

# DrawBoxWhiskers --
#    Draw the data in an XY-plot as box-and-whiskers
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    xcrd        Next x coordinate or a list of values
#    ycrd        Next y coordinate or a list of values
# Result:
#    None
# Side effects:
#    New data drawn in canvas
# Note:
#    We can do either a horizontal box (one y value) or
#    a vertical box (one x value). Not both
#
proc ::Plotchart::DrawBoxWhiskers { w series xcrd ycrd } {
    variable data_series
    variable scaling

    #
    # Check orientation
    #
    set type "?"
    if { [llength $xcrd] > 1 && [llength $ycrd] == 1 } {
        set type h
    }
    if { [llength $xcrd] == 1 && [llength $ycrd] > 1 } {
        set type v
    }
    if { $type == "?" } {
        return -code error "Use either a list of x values or a list of y values - not both"
    }

    #
    # Determine the quartiles:
    #
    # quartile1 is the 25% quantile
    # quartile2 is the 50% quantile (the median value)
    # quartile3 is the 75% quantile
    #
    # also
    # values between 'lower'/'upper' and outlower'/'outupper' are values within 1.5*IQR - 3*IQR (drawn as a dot)
    # values outside 'outlower'/'outupper' are values outside 3*IQR (drawn as a star)
    #
    # quartile1 is the 25% quantile
    # quartile2 is the 50% quantile (the median value)
    # quartile3 is the 75% quantile
    #
    # also
    # values between 'lower'/'upper' and outlower'/'outupper' are values within 1.5*IQR - 3*IQR (drawn as a dot)
    # values outside 'outlower'/'outupper' are values outside 3*IQR (drawn as a star)
    #
    if { $type == "h" } {
        set data [lsort -real -increasing $xcrd]
    } else {
        set data [lsort -real -increasing $ycrd]
    }
    set length    [llength $data]
    if { $length % 2 == 0 } {
        set lowerhalf [expr {($length-1)/2}]
        set upperhalf [expr {($length+1)/2}]
    } else {
        set lowerhalf [expr {$length/2-1}]
        set upperhalf [expr {$length/2+1}]
    }

    set quartile2 [DetermineMedian $data]
    set quartile1 [DetermineMedian [lrange $data 0 $lowerhalf]]
    set quartile3 [DetermineMedian [lrange $data $upperhalf end]]

    set hspread   [expr {$quartile3-$quartile1}]

    set lower     [expr {$quartile1-1.5*$hspread}]
    set upper     [expr {$quartile3+1.5*$hspread}]
    set outlower  [expr {$quartile1-3.0*$hspread}]
    set outupper  [expr {$quartile3+3.0*$hspread}]

    set whisker IQR
    if { [info exists data_series($w,$series,-whisker)] } {
        set whisker $data_series($w,$series,-whisker)
    }
    if { $whisker eq "extremes" } {
        set minimum [lindex $data 0]
        set maximum [lindex $data end]
    } elseif { $whisker eq "IQR" || $whisker eq "iqr" } {

        set minimum {}
        set maximum {}
        foreach value $data {
            if { $value >= $lower } {
                if { $minimum == {} || $minimum > $value } {
                    set minimum $value
                }
            }
            if { $value <= $upper } {
                if { $maximum == {} || $maximum < $value } {
                    set maximum $value
                }
            }
        }
    } elseif { $whisker eq "none"} {
        # nop
    } else {
        return -code error "unknown value '$whisker' for -whisker option"
    }

    #
    # Draw the box and whiskers
    #
    set colour "black"
    if { [info exists data_series($w,$series,-colour)] } {
        set colour $data_series($w,$series,-colour)
    }
    set mediancolour $colour
    if { [info exists data_series($w,$series,-mediancolour)] } {
        set mediancolour $data_series($w,$series,-mediancolour)
    }
    set mediancolour $colour
    if { [info exists data_series($w,$series,-mediancolour)] } {
       set mediancolour $data_series($w,$series,-mediancolour)
    }
    set filled "no"
    if { [info exists data_series($w,$series,-filled)] } {
        set filled $data_series($w,$series,-filled)
    }
    set fillcolour white
    if { [info exists data_series($w,$series,-fillcolour)] } {
       set fillcolour $data_series($w,$series,-fillcolour)
    }
    set boxwidth 10
    if { [info exists data_series($w,$series,-boxwidth)] } {
       set boxwidth $data_series($w,$series,-boxwidth)
    }
    set medianwidth 2
    if { [info exists data_series($w,$series,-medianwidth)] } {
       set medianwidth $data_series($w,$series,-medianwidth)
    }
    set whiskerwidth 1
    if { [info exists data_series($w,$series,-whiskerwidth)] } {
       set whiskerwidth $data_series($w,$series,-whiskerwidth)
    }

    if { $type == "h" } {
        #
        # Horizontal boxplot:
        #
        foreach {pxcrd1 pycrd2} [coordsToPixel $w $quartile1 $ycrd] {break}
        foreach {pxcrd2 pycrd2} [coordsToPixel $w $quartile2 $ycrd] {break}
        foreach {pxcrd3 pycrd2} [coordsToPixel $w $quartile3 $ycrd] {break}
        if {$whisker ne "none"} {
            foreach {pxcrdm pycrd1} [coordsToPixel $w $minimum $ycrd] {break}
            foreach {pxcrdM pycrd2} [coordsToPixel $w $maximum $ycrd] {break}
            set pycrd0h [expr {$pycrd1-$boxwidth/4}]
            set pycrd2h [expr {$pycrd1+$boxwidth/4}]
        } else {
            foreach {- pycrd1} [coordsToPixel $w 0 $ycrd] {break}
        }
        set pycrd0  [expr {$pycrd1-$boxwidth/2}]
        set pycrd2  [expr {$pycrd1+$boxwidth/2}]

        if {$whisker ne "none"} {
            #
            # Left whisker:
            #
            $w create line      $pxcrdm $pycrd1 $pxcrd1 $pycrd1 \
                                 -fill $colour -tag [list data data_$series] -width $whiskerwidth
            $w create line      $pxcrdm $pycrd0h $pxcrdm $pycrd2h \
                                 -fill $colour -tag [list data data_$series] -width $whiskerwidth
            # right whisker:
            #
            # Right whisker:
            #
            $w create line      $pxcrd3 $pycrd1 $pxcrdM $pycrd1 \
                                 -fill $colour -tag [list data data_$series] -width $whiskerwidth
            $w create line      $pxcrdM $pycrd0h $pxcrdM $pycrd2h \
                                 -fill $colour -tag [list data data_$series] -width $whiskerwidth
        }
        #
        # Box:
        #
        $w create rectangle $pxcrd1 $pycrd0 $pxcrd3 $pycrd2 \
            -outline $colour -fill $fillcolour -tag [list data data_$series]
        #
        # Median:
        #
        $w create line      $pxcrd2 $pycrd0 $pxcrd2 $pycrd2 -width $medianwidth \
                             -fill $mediancolour -tag [list data data_$series]

        if {$whisker eq "IQR"} {
            foreach value $data {
                if { $value < $outlower || $value > $outupper } {
                    foreach {px py} [coordsToPixel $w $value $ycrd] {break}
                    $w create text $px $py -text "*" -anchor c \
                                 -fill $colour -tag [list data data_$series]
                    continue
                }
                if { $value < $lower || $value > $upper } {
                    foreach {px py} [coordsToPixel $w $value $ycrd] {break}
                    $w create oval [expr {$px-2}] [expr {$py-2}] \
                                   [expr {$px+2}] [expr {$py+2}] \
                                 -fill $colour -tag [list data data_$series]
                    continue
                }
            }
        }
    } else {
        #
        # Vertical boxplot:
        #
        foreach {pxcrd2 pycrd1} [coordsToPixel $w $xcrd $quartile1] {break}
        foreach {pxcrd2 pycrd2} [coordsToPixel $w $xcrd $quartile2] {break}
        foreach {pxcrd2 pycrd3} [coordsToPixel $w $xcrd $quartile3] {break}
        if {$whisker ne "none"} {
            foreach {pxcrd1 pycrdm} [coordsToPixel $w $xcrd $minimum] {break}
            foreach {pxcrd2 pycrdM} [coordsToPixel $w $xcrd $maximum] {break}
            set pxcrd0h [expr {$pxcrd1-$boxwidth/4}]
            set pxcrd2h [expr {$pxcrd1+$boxwidth/4}]
        } else {
            foreach {pxcrd1 -} [coordsToPixel $w $xcrd 0] {break}
        }
        set pxcrd0  [expr {$pxcrd1-$boxwidth/2}]
        set pxcrd2  [expr {$pxcrd1+$boxwidth/2}]

        if {$whisker ne "none"} {
            #
            # Lower whisker:
            #
            $w create line      $pxcrd1 $pycrdm $pxcrd1 $pycrd1 \
                                 -fill $colour -tag [list data data_$series] -width $whiskerwidth
            $w create line      $pxcrd0h $pycrdm $pxcrd2h $pycrdm \
                                 -fill $colour -tag [list data data_$series] -width $whiskerwidth
            # upper whisker:
            #
            # Upper whisker:
            #
            $w create line      $pxcrd1 $pycrd3 $pxcrd1 $pycrdM \
                                 -fill $colour -tag [list data data_$series] -width $whiskerwidth
            $w create line      $pxcrd0h $pycrdM $pxcrd2h $pycrdM \
                                 -fill $colour -tag [list data data_$series] -width $whiskerwidth
        }
        #
        # Box:
        #
        $w create rectangle $pxcrd0 $pycrd1 $pxcrd2 $pycrd3 \
            -outline $colour -fill $fillcolour -tag [list data data_$series]
        #
        # Median:
        #
        $w create line      $pxcrd0 $pycrd2 $pxcrd2 $pycrd2 -width $medianwidth \
                             -fill $mediancolour -tag [list data data_$series]

        if {$whisker eq "IQR"} {
            foreach value $data {
                if { $value < $outlower || $value > $outupper } {
                    foreach {px py} [coordsToPixel $w $xcrd $value] {break}
                    $w create text $px $py -text "*" \
                                 -fill $colour -tag [list data data_$series]
                    continue
                }
                if { $value < $lower || $value > $upper } {
                    foreach {px py} [coordsToPixel $w $xcrd $value] {break}
                    $w create oval [expr {$px-3}] [expr {$py-3}] \
                                   [expr {$px+3}] [expr {$py+3}] \
                                 -fill $colour -tag [list data data_$series]
                    continue
                }
            }
        }
    }

    $w lower data
}

# DrawBoxData --
#    Draw the data in a boxplot
#    where either the x-axis or the y-axis consists of labels
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    label       Label on the x- or y-axis to put the box on
#    values      List of values to plot the box and whiskers for
# Result:
#    None
# Side effects:
#    New data drawn in canvas
#
proc ::Plotchart::DrawBoxData { w series label values } {
    variable config
    variable scaling
    variable settings

    set index [lsearch $config($w,axisnames) $label]
    if { $index == -1 } {
        return "Label $label not found on axis"
    }

    set coord [expr {$index + 1}]

    if { $settings($w,orientation) eq "vertical" } {
        DrawBoxWhiskers $w $series $coord $values
    } else {
        DrawBoxWhiskers $w $series $values $coord
    }
}

# DrawPie --
#    Draw the pie
# Arguments:
#    w           Name of the canvas
#    data        Data series (pairs of label-value)
# Result:
#    None
# Side effects:
#    Pie filled
#
proc ::Plotchart::DrawPie { w data } {
   variable data_series
   variable scaling
   variable config

   set pxmin $scaling($w,pxmin)
   set pymin $scaling($w,pymin)
   set pxmax $scaling($w,pxmax)
   set pymax $scaling($w,pymax)

   set colours $scaling(${w},colours)

   if {[llength ${data}] == 2} {
       # use canvas create oval as arc does not fill with colour for a full circle
       set colour [lindex ${colours} 0]
       ${w} create oval ${pxmin} ${pymin} ${pxmax} ${pymax} -fill ${colour} \
         -width $config($w,slice,outlinewidth) -outline $config($w,slice,outline)
       # text looks nicer at 45 degree
       set rad [expr {45.0 * 3.1415926 / 180.0}]
       set xtext [expr {(${pxmin}+${pxmax}+cos(${rad})*(${pxmax}-${pxmin}+20))/2}]
       set ytext [expr {(${pymin}+${pymax}-sin(${rad})*(${pymax}-${pymin}+20))/2}]
       foreach {label value} ${data} {
           break
       }
       if { $config($w,labels,shownumbers) } {
           if { $config($w,labels,format) ne "" } {
               set label [format $config($w,labels,formatright) $value $label]
           } else {
               set label [format $config($w,labels,format) $label $value]
           }
       }
       ${w} create text ${xtext} ${ytext} -text ${label} -anchor w -font $config($w,labels,font)
       set scaling($w,angles) {0 360}
   } else {
       #
       # Determine the scale for the values
       # (so we can draw the correct angles)
       #

       set newdata  {}
       set sum 0.0
       foreach {label value} $data {
           lappend newdata [list $value $label]
          set sum [expr {$sum + $value}]
       }
       set factor [expr {360.0/$sum}]

       set data $newdata
       if { $config($w,labels,sorted) } {
           set data [lsort -index 0 -real $newdata]
       }

       #
       # Draw the line piece
       #
       set angle_init $config($w,slice,startangle)
       set op $config($w,slice,direction)

       set sum     0.0
       set idx     0
       set segment 0

       array unset scaling ${w},angles
       array unset scaling ${w},extent
       set colours [CycleColours ${colours} [expr {[llength ${data}] / 2}]]

       foreach sublist $data {
          foreach {value label} $sublist {break}
          set colour [lindex $colours $idx]
          incr idx

          if { $value == "" } {
              break
          }

          set angle_bgn [expr $angle_init $op ($sum * $factor)]
          set angle_ext $op[expr {$value * $factor}]
          lappend scaling(${w},angles) [expr {int(${angle_bgn})}]
          lappend scaling(${w},extent) [expr {int(${angle_ext})}]

          $w create arc  $pxmin $pymin $pxmax $pymax \
                         -start $angle_bgn -extent $angle_ext \
                         -fill $colour -style pieslice -tag [list data segment_$segment] \
                         -width $config($w,slice,outlinewidth) -outline $config($w,slice,outline)

          set rad   [expr {($angle_bgn+0.5*$angle_ext)*3.1415926/180.0}]
          # hack for label positioning 'out' or 'in':
          if {$config($w,labels,placement) eq "out"} {
            set xtext [expr {($pxmin+$pxmax+cos($rad)*($pxmax-$pxmin+20))/2}]
            set ytext [expr {($pymin+$pymax-sin($rad)*($pymax-$pymin+20))/2}]
            if { $xtext > ($pxmin+$pxmax)/2 } {
               set dir w
            } else {
               set dir e
            }
          } elseif {$config($w,labels,placement) eq "in"} {
            set dir c
            set centerx [expr {$pxmax - ($pxmax-$pxmin)/2.0}]
            set centery [expr {$pymax - ($pymax-$pymin)/2.0}]
            # 33% from the center to the radius
            set xtext [expr {$centerx + cos($rad)*($pxmax-$pxmin)*0.33}]
            set ytext [expr {$centery - sin($rad)*($pymax-$pymin)*0.33}]
          }

          if { $config($w,labels,shownumbers) } {
              if { $dir eq "w" && $config($w,labels,formatright) ne "" } {
                  set label [format $config($w,labels,formatright) $value $label]
              } else {
                  set label [format $config($w,labels,format) $label $value]
              }
          }

          $w create text $xtext $ytext -text $label -anchor $dir -tag segment_$segment \
            -font $config($w,labels,font) -fill $config($w,labels,textcolor)

          $w bind segment_$segment <ButtonPress-1> [list ::Plotchart::PieExplodeSegment $w $segment 1]

          set sum [expr {$sum + $value}]
          incr segment
       }
   }
}

# DrawSpiralPie --
#    Draw the spiral pie
# Arguments:
#    w           Name of the canvas
#    data        Data series (pairs of label-value)
# Result:
#    None
# Side effects:
#    Pie filled
#
proc ::Plotchart::DrawSpiralPie { w data } {
   variable data_series
   variable scaling
   variable config

   set pxmin $scaling($w,pxmin)
   set pymin $scaling($w,pymin)
   set pxmax $scaling($w,pxmax)
   set pymax $scaling($w,pymax)

   set colours $scaling(${w},colours)

   if {[llength ${data}] == 2} {
       # use canvas create oval as arc does not fill with colour for a full circle
       set colour [lindex ${colours} 0]
       ${w} create oval ${pxmin} ${pymin} ${pxmax} ${pymax} -fill ${colour} \
         -width $config($w,slice,outlinewidth) -outline $config($w,slice,outline)
       # text looks nicer at 45 degree
       set rad [expr {45.0 * 3.1415926 / 180.0}]
       set xtext [expr {(${pxmin}+${pxmax}+cos(${rad})*(${pxmax}-${pxmin}+20))/2}]
       set ytext [expr {(${pymin}+${pymax}-sin(${rad})*(${pymax}-${pymin}+20))/2}]
       foreach {label value} ${data} {
           break
       }
       if { $config($w,labels,shownumbers) } {
           if { $config($w,labels,format) ne "" } {
               set label [format $config($w,labels,formatright) $value $label]
           } else {
               set label [format $config($w,labels,format) $label $value]
           }
       }

       ${w} create text ${xtext} ${ytext} -text ${label} -anchor w -font $config($w,labels,font)
       set scaling($w,angles) {0 360}
   } else {
       #
       # Determine the scale for the values
       # (so we can draw the correct radii)
       #
       set maxvalue [lindex $data 1]
       set newdata  {}
       foreach {label value} $data {
           lappend newdata [list $value $label]
           if { $maxvalue < $value } {
               set maxvalue $value
           }
       }
       set data $newdata
       if { $config($w,labels,sorted) } {
           set data [lsort -index 0 -real $newdata]
       }

       set factor [expr {1.0/sqrt($maxvalue)}]
       set dangle [expr {360.0/[llength $data]}]

       #
       # Draw the line piece
       #
       set angle_init $config($w,slice,startangle)
       set op         $config($w,slice,direction)

       set sum     0.0
       set idx     0
       set segment 0

       array unset scaling ${w},angles
       array unset scaling ${w},extent
       set colours [CycleColours ${colours} [llength ${data}]]

       foreach sublist $data {
          foreach {value label} $sublist {break}
          set colour [lindex $colours $idx]
          incr idx

          if { $value == "" } {
              break
          }

          set angle_bgn [expr $angle_init $op $sum]
          set angle_ext [expr $op $dangle]
          lappend scaling(${w},angles) [expr {int(${angle_bgn})}]
          lappend scaling(${w},extent) [expr {int(${angle_ext})}]

          set slicexmin [expr {0.5 * ($pxmax + $pxmin - sqrt($value) * $factor * ($pxmax-$pxmin))}]
          set slicexmax [expr {0.5 * ($pxmax + $pxmin + sqrt($value) * $factor * ($pxmax-$pxmin))}]
          set sliceymin [expr {0.5 * ($pymax + $pymin - sqrt($value) * $factor * ($pymax-$pymin))}]
          set sliceymax [expr {0.5 * ($pymax + $pymin + sqrt($value) * $factor * ($pymax-$pymin))}]

          $w create arc  $slicexmin $sliceymin $slicexmax $sliceymax \
                         -start $angle_bgn -extent $angle_ext \
                         -fill $colour -style pieslice -tag [list data segment_$segment] \
                         -width $config($w,slice,outlinewidth) -outline $config($w,slice,outline)

          set rad   [expr {($angle_bgn+0.5*$angle_ext)*3.1415926/180.0}]
          # hack for label positioning 'out' or 'in':
          if {$config($w,labels,placement) eq "out"} {
            set xtext [expr {($slicexmin+$slicexmax+cos($rad)*($slicexmax-$slicexmin+20))/2}]
            set ytext [expr {($sliceymin+$sliceymax-sin($rad)*($sliceymax-$sliceymin+20))/2}]
            if { $xtext > ($slicexmin+$sliceymax)/2 } {
               set dir w
            } else {
               set dir e
            }
          } elseif {$config($w,labels,placement) eq "in"} {
            set dir c
            set centerx [expr {$slicexmax - ($slicexmax-$slicexmin)/2.0}]
            set centery [expr {$sliceymax - ($sliceymax-$sliceymin)/2.0}]
            # 33% from the center to the radius
            set xtext [expr {$centerx + cos($rad)*($slicexmax-$slicexmin)*0.33}]
            set ytext [expr {$centery - sin($rad)*($sliceymax-$sliceymin)*0.33}]
          }

          if { $config($w,labels,shownumbers) } {
              if { $dir eq "w" && $config($w,labels,formatright) ne "" } {
                  set label [format $config($w,labels,formatright) $value $label]
              } else {
                  set label [format $config($w,labels,format) $label $value]
              }
          }

          $w create text $xtext $ytext -text $label -anchor $dir -tag segment_$segment \
            -font $config($w,labels,font) -fill $config($w,labels,textcolor)

          $w bind segment_$segment <ButtonPress-1> [list ::Plotchart::PieExplodeSegment $w $segment 1]

          set sum [expr {$sum + $dangle}]
          incr segment
       }
   }
}

# DrawPolarData --
#    Draw data given in polar coordinates
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    rad         Next radius
#    phi         Next angle (in degrees)
# Result:
#    None
# Side effects:
#    Data drawn in canvas
#
proc ::Plotchart::DrawPolarData { w series rad phi } {
   variable torad
   set xcrd [expr {$rad*cos($phi*$torad)}]
   set ycrd [expr {$rad*sin($phi*$torad)}]

   DrawData $w $series $xcrd $ycrd
}

# DrawVertBarData --
#    Draw the vertical bars
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    ydata       Series of y data
#    colour      The colour to use (optional)
#    dir         Direction if graded colours are used (see DrawGradientBackground)
#    brightness  Brighten (bright) or darken (dark) the colours
# Result:
#    None
# Side effects:
#    Data bars drawn in canvas
#
proc ::Plotchart::DrawVertBarData { w series ydata {colour black} {dir {}} {brightness bright}} {
   variable data_series
   variable scaling
   variable legend
   variable settings
   variable config

   #
   # Draw the bars
   #
   set x $scaling($w,xbase)

   #
   # set the colours
   #
   if {[llength ${colour}]} {
       set colours ${colour}
   } elseif {[info exists scaling(${w},colours)]} {
       set colours $scaling(${w},colours)
   } else {
       set colours {}
   }
   set colours [CycleColours ${colours} [llength ${ydata}]]

   #
   # Legend information
   #
   set legendcol [lindex $colours 0]
   set data_series($w,$series,-colour) $legendcol
   set data_series($w,$series,-type)   rectangle
   if { [info exists legend($w,canvas)] } {
       set legendw $legend($w,canvas)
       $legendw itemconfigure $series -fill $legendcol
   }

   set newbase {}

   set idx 0
   foreach yvalue $ydata ybase $scaling($w,ybase) {
      set colour [lindex ${colours} ${idx}]
      incr idx

      if { $yvalue == "" } {
          set yvalue 0.0
      }

      set xnext [expr {$x+$scaling($w,barwidth)}]
      set y     [expr {$yvalue+$ybase}]
      foreach {px1 py1} [coordsToPixel $w $x     $ybase] {break}
      foreach {px2 py2} [coordsToPixel $w $xnext $y    ] {break}

      if { $dir == {} } {
          $w create rectangle $px1 $py1 $px2 $py2 \
                         -fill $colour -outline $config($w,bar,outline) -tag [list data $w data_$series]
      } else {
          if { $brightness == "dark" } {
              set intensity black
          } else {
              set intensity white
          }
          DrawGradientBackground $w $colour $dir $intensity [list $px1 $py1 $px2 $py2]
      }

      if { $settings($w,showvalues) } {
          set pxtext [expr {($px1+$px2)/2.0}]
          set pytext [expr {$py2-5}]
          set text   [format $settings($w,valueformat) $yvalue]
          if { $settings($w,valuefont) == "" } {
              $w create text $pxtext $pytext -text $text -anchor s \
                         -fill $settings($w,valuecolour) -tag [list data $w data_$series]
          } else {
              $w create text $pxtext $pytext -text $text -anchor s \
                         -fill $settings($w,valuecolour) -tag [list data $w data_$series] \
                         -font $settings($w,valuefont)
          }
      }

      $w lower [list data && $w]

      set x [expr {$x+1.0}]

      lappend newbase $y
   }

   #
   # Prepare for the next series
   #
   if { $scaling($w,stacked) } {
      set scaling($w,ybase) $newbase
   }

   set scaling($w,xbase) [expr {$scaling($w,xbase)+$scaling($w,xshift)}]
}

# DrawHorizBarData --
#    Draw the horizontal bars
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    xdata       Series of x data
#    colour      The colour to use (optional)
#    dir         Direction if graded colours are used (see DrawGradientBackground)
#    brightness  Brighten (bright) or darken (dark) the colours
# Result:
#    None
# Side effects:
#    Data bars drawn in canvas
#
proc ::Plotchart::DrawHorizBarData { w series xdata {colour black} {dir {}} {brightness bright}} {
   variable data_series
   variable scaling
   variable legend
   variable settings
   variable config

   #
   # Draw the bars
   #
   set y $scaling($w,ybase)

   #
   # set the colours
   #
   if {[llength ${colour}]} {
       set colours ${colour}
   } elseif {[info exists scaling(${w},colours)]} {
       set colours $scaling(${w},colours)
   } else {
       set colours {}
   }
   set colours [CycleColours ${colours} [llength ${xdata}]]

   #
   # Legend information
   #
   set legendcol [lindex $colours 0]
   set data_series($w,$series,-colour) $legendcol
   if { [info exists legend($w,canvas)] } {
       set legendw $legend($w,canvas)
       $legendw itemconfigure $series -fill $legendcol
   }

   set newbase {}

   set idx 0
   foreach xvalue $xdata xbase $scaling($w,xbase) {
      set colour [lindex ${colours} ${idx}]
      incr idx

      if { $xvalue == "" } {
          set xvalue 0.0
      }

      set ynext [expr {$y+$scaling($w,barwidth)}]
      set x     [expr {$xvalue+$xbase}]
      foreach {px1 py1} [coordsToPixel $w $xbase $y    ] {break}
      foreach {px2 py2} [coordsToPixel $w $x     $ynext] {break}

      if { $dir == {} } {
          $w create rectangle $px1 $py1 $px2 $py2 \
                         -fill $colour -outline $config($w,bar,outline) -tag [list data $w data_$series]
      } else {
          if { $brightness == "dark" } {
              set intensity black
          } else {
              set intensity white
          }
          DrawGradientBackground $w $colour $dir $intensity [list $px1 $py1 $px2 $py2]
      }

      if { $settings($w,showvalues) } {
          set pytext [expr {($py1+$py2)/2.0}]
          set pxtext [expr {$px2+5}]
          set text   [format $settings($w,valueformat) $xvalue]
          if { $settings($w,valuefont) == "" } {
              $w create text $pxtext $pytext -text $text -anchor w \
                         -fill $settings($w,valuecolour) -tag [list data $w data_$series]
          } else {
              $w create text $pxtext $pytext -text $text -anchor w \
                         -fill $settings($w,valuecolour) -tag [list data $w data_$series] \
                         -font $settings($w,valuefont)
          }
      }

      $w lower [list data && $w]

      set y [expr {$y+1.0}]

      lappend newbase $x
   }

   #
   # Prepare for the next series
   #
   if { $scaling($w,stacked) } {
      set scaling($w,xbase) $newbase
   }

   set scaling($w,ybase) [expr {$scaling($w,ybase)+$scaling($w,yshift)}]
}

# DrawHistogramData --
#    Draw the vertical bars (or lines or symbols) for a histogram
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    xcrd        X coordinate (for the righthand side of the bar)
#    ycrd        Y coordinate
# Result:
#    None
# Side effects:
#    Data bars drawn in canvas
#
proc ::Plotchart::DrawHistogramData { w series xcrd ycrd } {
   variable data_series
   variable scaling

   #
   # Check for missing values (only y-value can be missing!)
   #
   if { $ycrd == "" } {
       set data_series($w,$series,x) $xcrd
       return
   }

   #
   # Draw the bar/line
   #
   set colour "black"
   if { [info exists data_series($w,$series,-colour)] } {
      set colour $data_series($w,$series,-colour)
   }
   set fillcolour "black"
   if { [info exists data_series($w,$series,-fillcolour)] } {
      set fillcolour $data_series($w,$series,-fillcolour)
   }
   set width 1
   if { [info exists data_series($w,$series,-width)] } {
      set width $data_series($w,$series,-width)
   }
   set style "filled"
   if { [info exists data_series($w,$series,-style)] } {
      set style $data_series($w,$series,-style)
   }
   if { $style == "symbol" } {
       set symbol "plus"
       if { [info exists data_series($w,$series,-symbol)] } {
           set symbol $data_series($w,$series,-symbol)
       }
   }

   foreach {pxcrd pycrd} [coordsToPixel $w $xcrd $ycrd] {break}

   if { [info exists data_series($w,$series,x)] } {
      set xold       $data_series($w,$series,x)
      set pystair    $data_series($w,$series,pystair)
   } else {
      set xold       $scaling($w,xmin)
      set pystair    $scaling($w,pymax)
   }
   set yold $scaling($w,ymin)
   foreach {pxold pyold} [coordsToPixel $w $xold $yold] {break}

   switch -- $style {
       "filled" {
           $w create rectangle $pxold $pyold $pxcrd $pycrd \
                -fill $fillcolour -outline {} -tag [list data $w data_$series]
           $w create line $pxold $pystair $pxold $pycrd $pxcrd $pycrd \
                -fill $colour -width $width -tag [list data $w data_$series]
       }
       "stair" {
           $w create line $pxold $pystair $pxold $pycrd $pxcrd $pycrd \
                -fill $colour -width $width -tag [list data $w data_$series]
       }
       "spike" {
           $w create line $pxcrd $pyold $pxcrd $pycrd \
                -fill $colour -width $width -tag [list data $w data_$series]
       }
       "plateau" {
           $w create line $pxold $pycrd $pxold $pycrd $pxcrd $pycrd \
                -fill $colour -width $width -tag [list data $w data_$series]
       }
       "symbol" {
           DrawSymbolPixel $w $series $pxcrd $pycrd $symbol $colour [list data $w data_$series]
       }
   }

   $w lower [list data && $w]

   set data_series($w,$series,x)       $xcrd
   set data_series($w,$series,pystair) $pycrd

   #
   # Store the data for use in bindlast subcommand
   #
   set data_series($w,$series,px1)     $pxold
   set data_series($w,$series,py1)     $pyold
   set data_series($w,$series,px2)     $pxcrd
   set data_series($w,$series,py2)     $pycrd

   if { $style == "symbol" } {
       set data_series($w,$series,px1)     $pxcrd
       set data_series($w,$series,py1)     $pycrd
   }
}

# DrawHistogramCumulative --
#    Draw the vertical bars for a histogram - accumulate the data
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    xcrd        X coordinate (for the righthand side of the bar)
#    ycrd        Y coordinate
# Result:
#    None
# Side effects:
#    Data bars drawn in canvas
#
proc ::Plotchart::DrawHistogramCumulative { w series xcrd ycrd } {
   variable data_series
   variable scaling

   #
   # Check for missing values (only y-value can be missing!)
   #
   if { $ycrd == "" } {
       set data_series($w,$series,x) $xcrd
       return
   }

   #
   # Prepare the data
   #
   if { [info exists data_series($w,$series,y)] } {
      set ycrd [expr {$data_series($w,$series,y) + $ycrd}]
   }

   DrawHistogramData $w $series $xcrd $ycrd

   set data_series($w,$series,y) $ycrd
}

# DrawTimePeriod --
#    Draw a period
# Arguments:
#    w           Name of the canvas
#    text        Text to identify the "period" item
#    time_begin  Start time
#    time_end    Stop time
#    colour      The colour to use (optional)
# Result:
#    None
# Side effects:
#    Data bars drawn in canvas
#
proc ::Plotchart::DrawTimePeriod { w text time_begin time_end {colour black}} {
   variable data_series
   variable scaling

   #
   # Draw the text first
   #
   set ytext [expr {$scaling($w,current)+0.5*$scaling($w,dy)}]
   foreach {x y} [coordsToPixel $w $scaling($w,xmin) $ytext] {break}

   $w create text 5 $y -text $text -anchor w \
       -tags [list vertscroll above item_[expr {int($scaling($w,current))}]]

   #
   # Draw the bar to indicate the period
   #
   set xmin  [clock scan $time_begin]
   set xmax  [clock scan $time_end]
   set ybott [expr {$scaling($w,current)+$scaling($w,dy)}]

   foreach {x1 y1} [coordsToPixel $w $xmin $scaling($w,current)] {break}
   foreach {x2 y2} [coordsToPixel $w $xmax $ybott              ] {break}

   $w create rectangle $x1 $y1 $x2 $y2 -fill $colour \
       -tags [list $w vertscroll horizscroll below item_[expr {int($scaling($w,current))}]]

   ReorderChartItems $w

   set scaling($w,current) [expr {$scaling($w,current)-1.0}]

   RescaleChart $w
}

# DrawTimeVertLine --
#    Draw a vertical line with a label
# Arguments:
#    w           Name of the canvas
#    text        Text to identify the line
#    time        Time for which the line is drawn
# Result:
#    None
# Side effects:
#    Line drawn in canvas
#
proc ::Plotchart::DrawTimeVertLine { w text time {colour black}} {
   variable data_series
   variable scaling

   #
   # Draw the text first
   #
   set xtime [clock scan $time]
   #set ytext [expr {$scaling($w,ymax)-0.5*$scaling($w,dy)}]
   set ytext $scaling($w,ymax)
   foreach {x y} [coordsToPixel $w $xtime $ytext] {break}
   set y [expr {$y-5}]

   $w create text $x $y -text $text -anchor sw -tags [list $w horizscroll timeline]

   #
   # Draw the line
   #
   foreach {x1 y1} [coordsToPixel $w $xtime $scaling($w,ymin)] {break}
   foreach {x2 y2} [coordsToPixel $w $xtime $scaling($w,ymax)] {break}

   $w create line $x1 $y1 $x2 $y2 -fill black -tags [list $w horizscroll timeline tline]

   $w raise topmask
}

# DrawTimeMilestone --
#    Draw a "milestone"
# Arguments:
#    w           Name of the canvas
#    text        Text to identify the line
#    time        Time for which the milestone is drawn
#    colour      Optionally the colour
# Result:
#    None
# Side effects:
#    Line drawn in canvas
#
proc ::Plotchart::DrawTimeMilestone { w text time {colour black}} {
   variable data_series
   variable scaling

   #
   # Draw the text first
   #
   set ytext [expr {$scaling($w,current)+0.5*$scaling($w,dy)}]
   foreach {x y} [coordsToPixel $w $scaling($w,xmin) $ytext] {break}

   $w create text 5 $y -text $text -anchor w \
       -tags [list vertscroll above item_[expr {int($scaling($w,current))}]]

   #
   # Draw an upside-down triangle to indicate the time
   #
   set xcentre [clock scan $time]
   set ytop    $scaling($w,current)
   set ybott   [expr {$scaling($w,current)+0.8*$scaling($w,dy)}]

   foreach {x1 y1} [coordsToPixel $w $xcentre $ybott] {break}
   foreach {x2 y2} [coordsToPixel $w $xcentre $ytop]  {break}

   set x2 [expr {$x1-0.4*($y1-$y2)}]
   set x3 [expr {$x1+0.4*($y1-$y2)}]
   set y3 $y2

   $w create polygon $x1 $y1 $x2 $y2 $x3 $y3 -fill $colour \
       -tags [list $w vertscroll horizscroll below item_[expr {int($scaling($w,current))}]]

   ReorderChartItems $w

   set scaling($w,current) [expr {$scaling($w,current)-1.0}]

   RescaleChart $w
}

# ScaleItems --
#    Scale all items by a given factor
# Arguments:
#    w           Name of the canvas
#    xcentre     X-coordinate of centre
#    ycentre     Y-coordinate of centre
#    factor      The factor to scale them by
# Result:
#    None
# Side effects:
#    All items are scaled by the given factor and the
#    world coordinates are adjusted.
#
proc ::Plotchart::ScaleItems { w xcentre ycentre factor } {
   variable scaling

   $w scale all $xcentre $ycentre $factor $factor

   foreach {xc yc} [pixelToCoords $w $xcentre $ycentre] {break}

   set rfact               [expr {1.0/$factor}]
   set scaling($w,xfactor) [expr {$scaling($w,xfactor)*$factor}]
   set scaling($w,yfactor) [expr {$scaling($w,yfactor)*$factor}]
   set scaling($w,xmin)    [expr {(1.0-$rfact)*$xc+$rfact*$scaling($w,xmin)}]
   set scaling($w,xmax)    [expr {(1.0-$rfact)*$xc+$rfact*$scaling($w,xmax)}]
   set scaling($w,ymin)    [expr {(1.0-$rfact)*$yc+$rfact*$scaling($w,ymin)}]
   set scaling($w,ymax)    [expr {(1.0-$rfact)*$yc+$rfact*$scaling($w,ymax)}]
}

# MoveItems --
#    Move all items by a given vector
# Arguments:
#    w           Name of the canvas
#    xmove       X-coordinate of move vector
#    ymove       Y-coordinate of move vector
# Result:
#    None
# Side effects:
#    All items are moved by the given vector and the
#    world coordinates are adjusted.
#
proc ::Plotchart::MoveItems { w xmove ymove } {
   variable scaling

   $w move all $xmove $ymove

   set dx                  [expr {$scaling($w,xfactor)*$xmove}]
   set dy                  [expr {$scaling($w,yfactor)*$ymove}]
   set scaling($w,xmin)    [expr {$scaling($w,xmin)+$dx}]
   set scaling($w,xmax)    [expr {$scaling($w,xmax)+$dx}]
   set scaling($w,ymin)    [expr {$scaling($w,ymin)+$dy}]
   set scaling($w,ymax)    [expr {$scaling($w,ymax)+$dy}]
}

# DrawIsometricData --
#    Draw the data in an isometric plot
# Arguments:
#    w           Name of the canvas
#    type        Type of data
#    args        Coordinates and so on
# Result:
#    None
# Side effects:
#    New data drawn in canvas
#
proc ::Plotchart::DrawIsometricData { w type args } {
   variable data_series

   #
   # What type of data?
   #
   if { $type == "rectangle" } {
      foreach {x1 y1 x2 y2 colour} [concat $args "black"] {break}
      foreach {px1 py1} [coordsToPixel $w $x1 $y1] {break}
      foreach {px2 py2} [coordsToPixel $w $x2 $y2] {break}
      $w create rectangle $px1 $py1 $px2 $py2 \
                     -outline $colour -tag [list $w data]
      $w lower data
   }

   if { $type == "filled-rectangle" } {
      foreach {x1 y1 x2 y2 colour} [concat $args "black"] {break}
      foreach {px1 py1} [coordsToPixel $w $x1 $y1] {break}
      foreach {px2 py2} [coordsToPixel $w $x2 $y2] {break}
      $w create rectangle $px1 $py1 $px2 $py2 \
                     -outline $colour -fill $colour -tag [list $w data]
      $w lower [list data && $w]
   }

   if { $type == "filled-circle" } {
      foreach {x1 y1 rad colour} [concat $args "black"] {break}
      set x2 [expr {$x1+$rad}]
      set y2 [expr {$y1+$rad}]
      set x1 [expr {$x1-$rad}]
      set y1 [expr {$y1-$rad}]
      foreach {px1 py1} [coordsToPixel $w $x1 $y1] {break}
      foreach {px2 py2} [coordsToPixel $w $x2 $y2] {break}
      $w create oval $px1 $py1 $px2 $py2 \
                     -outline $colour -fill $colour -tag [list $w data]
      $w lower [list data && $w]
   }

   if { $type == "circle" } {
      foreach {x1 y1 rad colour} [concat $args "black"] {break}
      set x2 [expr {$x1+$rad}]
      set y2 [expr {$y1+$rad}]
      set x1 [expr {$x1-$rad}]
      set y1 [expr {$y1-$rad}]
      foreach {px1 py1} [coordsToPixel $w $x1 $y1] {break}
      foreach {px2 py2} [coordsToPixel $w $x2 $y2] {break}
      $w create oval $px1 $py1 $px2 $py2 \
                     -outline $colour -tag [list $w data]
      $w lower [list data && $w]
   }

}

# BackgroundColour --
#    Set the background colour or other aspects of the background
# Arguments:
#    w           Name of the canvas
#    part        Which part: axes or plot
#    colour      Colour to use (or if part is "image", name of the image)
#    dir         Direction of increasing whiteness (optional, for "gradient"
#    brightness  Brighten (bright) or darken (dark) the colours
#
# Result:
#    None
# Side effect:
#    Colour of the relevant part is changed
#
proc ::Plotchart::BackgroundColour { w part colour {dir {}} {brighten bright}} {
    if { $part == "axes" } {
        $w configure -highlightthickness 0
        $w itemconfigure mask -fill $colour -outline $colour
    }
    if { $part == "plot" } {
        $w configure -highlightthickness 0
        $w configure -background $colour
    }
    if { $part == "gradient" } {
          if { $brighten == "dark" } {
              set intensity black
          } else {
              set intensity white
          }
        DrawGradientBackground $w $colour $dir $intensity
    }
    if { $part == "image" } {
        DrawImageBackground $w $colour
    }
}

# DrawRadialSpokes --
#    Draw the spokes of the radial chart
# Arguments:
#    w           Name of the canvas
#    names       Names of the spokes
# Result:
#    None
# Side effects:
#    Radial chart filled in
#
proc ::Plotchart::DrawRadialSpokes { w names } {
   variable settings
   variable scaling

   set pxmin $scaling($w,pxmin)
   set pymin $scaling($w,pymin)
   set pxmax $scaling($w,pxmax)
   set pymax $scaling($w,pymax)

   $w create oval $pxmin $pymin $pxmax $pymax -outline black

   set dangle [expr {2.0 * 3.1415926 / [llength $names]}]
   set angle  0.0
   set xcentr [expr {($pxmin+$pxmax)/2.0}]
   set ycentr [expr {($pymin+$pymax)/2.0}]

   foreach name $names {
       set xtext  [expr {$xcentr+cos($angle)*($pxmax-$pxmin+20)/2}]
       set ytext  [expr {$ycentr-sin($angle)*($pymax-$pymin+20)/2}]
       set xspoke [expr {$xcentr+cos($angle)*($pxmax-$pxmin)/2}]
       set yspoke [expr {$ycentr-sin($angle)*($pymax-$pymin)/2}]

       if { cos($angle) >= 0.0 } {
           set anchor w
       } else {
           set anchor e
       }

       if { abs($xspoke-$xcentr) < 2 } {
           set xspoke $xcentr
       }
       if { abs($yspoke-$ycentr) < 2 } {
           set yspoke $ycentr
       }

       $w create text $xtext $ytext -text $name -anchor $anchor
       $w create line $xcentr $ycentr $xspoke $yspoke -fill black

       set angle [expr {$angle+$dangle}]
   }
}

# DrawRadial --
#    Draw the data for the radial chart
# Arguments:
#    w           Name of the canvas
#    values      Values for each spoke
#    colour      Colour of the line
#    thickness   Thickness of the line (optional)
# Result:
#    None
# Side effects:
#    New line drawn
#
proc ::Plotchart::DrawRadial { w values colour {thickness 1} } {
   variable data_series
   variable settings
   variable scaling

   if { [llength $values] != $settings($w,number) } {
       return -code error "Incorrect number of data given - should be $settings($w,number)"
   }

   set pxmin $scaling($w,pxmin)
   set pymin $scaling($w,pymin)
   set pxmax $scaling($w,pxmax)
   set pymax $scaling($w,pymax)

   set dangle [expr {2.0 * 3.1415926 / [llength $values]}]
   set angle  0.0
   set xcentr [expr {($pxmin+$pxmax)/2.0}]
   set ycentr [expr {($pymin+$pymax)/2.0}]

   set coords {}

   if { ! [info exists data_series($w,base)] } {
       set data_series($w,base) {}
       foreach value $values {
           lappend data_series($w,base) 0.0
       }
   }

   set newbase {}
   foreach value $values base $data_series($w,base) {
       if { $settings($w,style) != "lines" } {
           set value [expr {$value+$base}]
       }
       set factor [expr {$value/$settings($w,scale)}]
       set xspoke [expr {$xcentr+$factor*cos($angle)*($pxmax-$pxmin)/2}]
       set yspoke [expr {$ycentr-$factor*sin($angle)*($pymax-$pymin)/2}]

       if { abs($xspoke-$xcentr) < 2 } {
           set xspoke $xcentr
       }
       if { abs($yspoke-$ycentr) < 2 } {
           set yspoke $ycentr
       }

       lappend coords $xspoke $yspoke
       lappend newbase $value
       set angle [expr {$angle+$dangle}]
   }

   set data_series($w,base) $newbase

   if { $settings($w,style) == "filled" } {
       set fillcolour $colour
   } else {
       set fillcolour ""
   }

   set id [$w create polygon $coords -outline $colour -width $thickness -fill $fillcolour -tags [list data $w]]
   $w lower $id
}

# DrawTrendLine --
#    Draw a trend line based on the given data in an XY-plot
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    xcrd        Next x coordinate
#    ycrd        Next y coordinate
# Result:
#    None
# Side effects:
#    New/updated trend line drawn in canvas
#
proc ::Plotchart::DrawTrendLine { w series xcrd ycrd } {
    variable data_series
    variable scaling

    #
    # Check for missing values
    #
    if { $xcrd == "" || $ycrd == "" } {
        return
    }

    #
    # Compute the coefficients of the line
    #
    if { [info exists data_series($w,$series,xsum)] } {
        set nsum  [expr {$data_series($w,$series,nsum)  + 1.0}]
        set xsum  [expr {$data_series($w,$series,xsum)  + $xcrd}]
        set x2sum [expr {$data_series($w,$series,x2sum) + $xcrd*$xcrd}]
        set ysum  [expr {$data_series($w,$series,ysum)  + $ycrd}]
        set xysum [expr {$data_series($w,$series,xysum) + $ycrd*$xcrd}]
    } else {
        set nsum  [expr {1.0}]
        set xsum  [expr {$xcrd}]
        set x2sum [expr {$xcrd*$xcrd}]
        set ysum  [expr {$ycrd}]
        set xysum [expr {$ycrd*$xcrd}]
    }

    if { $nsum*$x2sum != $xsum*$xsum } {
        set a [expr {($nsum*$xysum-$xsum*$ysum)/($nsum*$x2sum - $xsum*$xsum)}]
    } else {
        set a 0.0
    }
    set b [expr {($ysum-$a*$xsum)/$nsum}]

    set xmin $scaling($w,xmin)
    set xmax $scaling($w,xmax)

    foreach {pxmin pymin} [coordsToPixel $w $xmin [expr {$a*$xmin+$b}]] {break}
    foreach {pxmax pymax} [coordsToPixel $w $xmax [expr {$a*$xmax+$b}]] {break}

    #
    # Draw the actual line
    #
    set colour "black"
    if { [info exists data_series($w,$series,-colour)] } {
        set colour $data_series($w,$series,-colour)
    }

    if { [info exists data_series($w,$series,trend)] } {
        $w coords $data_series($w,$series,trend) $pxmin $pymin $pxmax $pymax
    } else {
        set data_series($w,$series,trend) \
            [$w create line $pxmin $pymin $pxmax $pymax -fill $colour -tag [list data $w data_$series]]
    }

    $w lower [list data && $w]

    set data_series($w,$series,nsum)  $nsum
    set data_series($w,$series,xsum)  $xsum
    set data_series($w,$series,x2sum) $x2sum
    set data_series($w,$series,ysum)  $ysum
    set data_series($w,$series,xysum) $xysum
}

# VectorConfigure --
#    Set configuration options for vectors
# Arguments:
#    w           Name of the canvas
#    series      Data series (identifier for vectors)
#    args        Pairs of configuration options:
#                -scale|-colour|-centred|-type {cartesian|polar|nautical}
# Result:
#    None
# Side effects:
#    Configuration options are stored
#
proc ::Plotchart::VectorConfigure { w series args } {
    variable data_series
    variable scaling

    foreach {option value} $args {
        switch -- $option {
            "-scale" {
                if { $value > 0.0 } {
                    set scaling($w,$series,vectorscale) $value
                } else {
                    return -code error "Scale factor must be positive"
                }
            }
            "-colour" - "-color" {
                set data_series($w,$series,vectorcolour) $value
            }
            "-centered" - "-centred" {
                set data_series($w,$series,vectorcentred) $value
            }
            "-type" {
                if { [lsearch {cartesian polar nautical} $value] >= 0 } {
                    set data_series($w,$series,vectortype) $value
                } else {
                    return -code error "Unknown vector components option: $value"
                }
            }
            default {
                return -code error "Unknown vector option: $option ($value)"
            }
        }
    }
}

# DrawVector --
#    Draw a vector at the given coordinates with the given components
# Arguments:
#    w           Name of the canvas
#    series      Data series (identifier for the vectors)
#    xcrd        X coordinate of start or centre
#    ycrd        Y coordinate of start or centre
#    ucmp        X component or length
#    vcmp        Y component or angle
# Result:
#    None
# Side effects:
#    New arrow drawn in canvas
#
proc ::Plotchart::DrawVector { w series xcrd ycrd ucmp vcmp } {
    variable data_series
    variable scaling

    #
    # Check for missing values
    #
    if { $xcrd == "" || $ycrd == "" } {
        return
    }
    #
    # Check for missing values
    #
    if { $ucmp == "" || $vcmp == "" } {
        return
    }

    #
    # Get the options
    #
    set scalef  1.0
    set colour  black
    set centred 0
    set type    cartesian
    if { [info exists scaling($w,$series,vectorscale)] } {
        set scalef $scaling($w,$series,vectorscale)
    }
    if { [info exists data_series($w,$series,vectorcolour)] } {
        set colour $data_series($w,$series,vectorcolour)
    }
    if { [info exists data_series($w,$series,vectorcentred)] } {
        set centred $data_series($w,$series,vectorcentred)
    }
    if { [info exists data_series($w,$series,vectortype)] } {
        set type $data_series($w,$series,vectortype)
    }

    #
    # Compute the coordinates of beginning and end of the arrow
    #
    switch -- $type {
        "polar" {
            set x1 [expr {$ucmp * cos( 3.1415926 * $vcmp / 180.0 ) }]
            set y1 [expr {$ucmp * sin( 3.1415926 * $vcmp / 180.0 ) }]
            set ucmp $x1
            set vcmp $y1
        }
        "nautical" {
            set x1 [expr {$ucmp * sin( 3.1415926 * $vcmp / 180.0 ) }]
            set y1 [expr {$ucmp * cos( 3.1415926 * $vcmp / 180.0 ) }]
            set ucmp $x1
            set vcmp $y1
        }
    }

    set u1 [expr {$scalef * $ucmp}]
    set v1 [expr {$scalef * $vcmp}]

    foreach {x1 y1} [coordsToPixel $w $xcrd $ycrd] {break}

    if { $centred } {
        set x1 [expr {$x1 - 0.5 * $u1}]
        set y1 [expr {$y1 + 0.5 * $v1}]
    }

    set x2 [expr {$x1 + $u1}]
    set y2 [expr {$y1 - $v1}]

    #
    # Draw the arrow
    #
    $w create line $x1 $y1 $x2 $y2 -fill $colour -tag [list data $w data_$series] -arrow last
    $w lower data
}

# DotConfigure --
#    Set configuration options for dots
# Arguments:
#    w           Name of the canvas
#    series      Data series (identifier for dots)
#    args        Pairs of configuration options:
#                -radius|-colour|-classes {value colour ...}|-outline|-scalebyvalue|
#                -scale
# Result:
#    None
# Side effects:
#    Configuration options are stored
#
proc ::Plotchart::DotConfigure { w series args } {
    variable data_series
    variable scaling

    foreach {option value} $args {
        switch -- $option {
            "-scale" {
                if { $value > 0.0 } {
                    set scaling($w,$series,dotscale) $value
                } else {
                    return -code error "Scale factor must be positive"
                }
            }
            "-colour" - "-color" {
                set data_series($w,$series,dotcolour) $value
            }
            "-radius" {
                set data_series($w,$series,dotradius) $value
            }
            "-scalebyvalue" {
                set data_series($w,$series,dotscalebyvalue) $value
            }
            "-outline" {
                set data_series($w,$series,dotoutline) $value
            }
            "-classes" {
                set data_series($w,$series,dotclasses) $value
            }
            "-3deffect" {
                set data_series($w,$series,dot3deffect) $value
            }
            default {
                return -code error "Unknown dot option: $option ($value)"
            }
        }
    }
}

# DrawDot --
#    Draw a dot at the given coordinates, size and colour based on the given value
# Arguments:
#    w           Name of the canvas
#    series      Data series (identifier for the vectors)
#    xcrd        X coordinate of start or centre
#    ycrd        Y coordinate of start or centre
#    value       Value to be used
# Result:
#    None
# Side effects:
#    New oval drawn in canvas
#
proc ::Plotchart::DrawDot { w series xcrd ycrd value } {
    variable data_series
    variable scaling

    #
    # Check for missing values
    #
    if { $xcrd == "" || $ycrd == "" || $value == "" } {
        return
    }

    #
    # Get the options
    #
    set scalef   1.0
    set colour   black
    set usevalue 1
    set outline  black
    set radius   3
    set classes  {}
    set use3deffect off
    if { [info exists scaling($w,$series,dotscale)] } {
        set scalef $scaling($w,$series,dotscale)
    }
    if { [info exists data_series($w,$series,dotcolour)] } {
        set colour $data_series($w,$series,dotcolour)
    }
    if { [info exists data_series($w,$series,dotoutline)] } {
        set outline {}
        if { $data_series($w,$series,dotoutline) } {
            set outline black
        }
    }
    if { [info exists data_series($w,$series,dotradius)] } {
        set radius $data_series($w,$series,dotradius)
    }
    if { [info exists data_series($w,$series,dotclasses)] } {
        set classes $data_series($w,$series,dotclasses)
    }
    if { [info exists data_series($w,$series,dotscalebyvalue)] } {
        set usevalue $data_series($w,$series,dotscalebyvalue)
    }
    if { [info exists data_series($w,$series,dot3deffect)] } {
        set use3deffect $data_series($w,$series,dot3deffect)
    }

    #
    # Compute the radius and the colour
    #
    if { $usevalue } {
        set radius [expr {$scalef * $value}]
    }
    if { $classes != {} } {
        foreach {limit col} $classes {
            if { $value < $limit } {
                set colour $col
                break
            }
        }
    }

    foreach {x y} [coordsToPixel $w $xcrd $ycrd] {break}

    set x1 [expr {$x - $radius}]
    set y1 [expr {$y - $radius}]
    set x2 [expr {$x + $radius}]
    set y2 [expr {$y + $radius}]

    #
    # Draw the oval
    #
    $w create oval $x1 $y1 $x2 $y2 -fill $colour -tag [list data $w data_$series] -outline $outline

    #
    # 3D effect
    #
    if { $use3deffect } {

        set xcentre [expr {$x - 0.6 * $radius}]
        set ycentre [expr {$y - 0.6 * $radius}]

        set factor    1.0
        set newradius $radius
        while { $newradius > 2 } {

            set factor    [expr {$factor * 0.8}]
            set newradius [expr {$radius * $factor}]
            set newcolour [BrightenColour $colour white [expr {1.0-$factor**2}]]

            set newdot [$w create oval $x1 $y1 $x2 $y2 -fill $newcolour -outline {} \
                            -tag [list data $w data_$series]]
            $w scale $newdot $xcentre $ycentre $factor $factor
        }
    }

    $w lower [list data && $w]
}

# DrawLog*Dot, DrawPolarDot --
#    Draw a dot at the given coordinates - variants for logarithmic axes and polar axis
# Arguments:
#    w           Name of the canvas
#    series      Data series (identifier for the vectors)
#    xcrd        X coordinate of start or centre
#    ycrd        Y coordinate of start or centre
#    value       Value to be used
# Result:
#    None
# Side effects:
#    New oval drawn in canvas
#
proc ::Plotchart::DrawLogXDot { w series xcrd ycrd value } {

    DrawDot $w $series [expr {log10($xcrd)}] $ycrd $value
}

proc ::Plotchart::DrawLogYDot { w series xcrd ycrd value } {

    DrawDot $w $series $xcrd [expr {log10($ycrd)}] $value
}

proc ::Plotchart::DrawLogXLogYDot { w series xcrd ycrd value } {

    DrawDot $w $series [expr {log10($xcrd)}] [expr {log10($ycrd)}] $value
}

proc ::Plotchart::DrawPolarDot { w series rad phi value } {
   variable torad
   set xcrd [expr {$rad*cos($phi*$torad)}]
   set ycrd [expr {$rad*sin($phi*$torad)}]

   DrawDot $w $series $xcrd $ycrd $value
}

# DrawRchart --
#    Draw data together with two horizontal lines representing the
#    expected range
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    xcrd        X coordinate of the data point
#    ycrd        Y coordinate of the data point
# Result:
#    None
# Side effects:
#    New data point drawn, lines updated
#
proc ::Plotchart::DrawRchart { w series xcrd ycrd } {
    variable data_series
    variable scaling

    #
    # Check for missing values
    #
    if { $xcrd == "" || $ycrd == "" } {
        return
    }

    #
    # In any case, draw the data point
    #
    DrawData $w $series $xcrd $ycrd

    #
    # Compute the expected range
    #
    if { ! [info exists data_series($w,$series,rchart)] } {
        set data_series($w,$series,rchart) $ycrd
    } else {
        lappend data_series($w,$series,rchart) $ycrd

        if { [llength $data_series($w,$series,rchart)] < 2 } {
            return
        }

        set filtered $data_series($w,$series,rchart)
        set outside  1
        while { $outside } {
            set data     $filtered
            foreach {ymin ymax} [RchartValues $data] {break}
            set filtered {}
            set outside  0
            foreach y $data {
                if { $y < $ymin || $y > $ymax } {
                    set outside 1
                } else {
                    lappend filtered $y
                }
            }
        }

        #
        # Draw the limit lines
        #
        if { [info exists data_series($w,$series,rchartlimits)] } {
            eval $w delete $data_series($w,$series,rchartlimits)
        }

        set colour "black"
        if { [info exists data_series($w,$series,-colour)] } {
            set colour $data_series($w,$series,-colour)
        }

        set xmin $scaling($w,xmin)
        set xmax $scaling($w,xmax)

        foreach {pxmin pymin} [coordsToPixel $w $xmin $ymin] {break}
        foreach {pxmax pymax} [coordsToPixel $w $xmax $ymax] {break}


        set data_series($w,$series,rchartlimits) [list \
            [$w create line $pxmin $pymin $pxmax $pymin -fill $colour -tag [list data $w data_$series]] \
            [$w create line $pxmin $pymax $pxmax $pymax -fill $colour -tag [list data $w data_$series]] \
        ]
    }
}

# RchartValues --
#    Compute the expected range for a series of data
# Arguments:
#    data        Data to be examined
# Result:
#    Expected minimum and maximum
#
proc ::Plotchart::RchartValues { data } {
    set sum   0.0
    set sum2  0.0
    set ndata [llength $data]

    if { $ndata <= 1 } {
        return [list $data $data]
    }

    foreach v $data {
        set sum   [expr {$sum  + $v}]
        set sum2  [expr {$sum2 + $v*$v}]
    }

    if { $ndata < 2 } {
       return [list $v $v]
    }

    set variance [expr {($sum2 - $sum*$sum/double($ndata))/($ndata-1.0)}]
    if { $variance < 0.0 } {
        set variance 0.0
    }

    set vmean [expr {$sum/$ndata}]
    set stdev [expr {sqrt($variance)}]
    set vmin  [expr {$vmean - 3.0 * $stdev}]
    set vmax  [expr {$vmean + 3.0 * $stdev}]

    return [list $vmin $vmax]
}

# ReorderChartItems --
#    Rearrange the drawing order of time and Gantt chart items
# Arguments:
#    w           Canvas widget containing them
# Result:
#    None
#
proc ::Plotchart::ReorderChartItems { w } {

    $w lower above
    $w lower vertmask
    $w lower tline
    $w lower below
    $w lower lowest

}

# RescaleChart --
#    Reset the scaling of the scrollbar(s) for time and Gantt charts
# Arguments:
#    w           Canvas widget containing them
# Result:
#    None
# Note:
#    To be called after scaling($w,current) has been updated
#    or a new time line has been added
#
proc ::Plotchart::RescaleChart { w } {
    variable scaling

    if { [info exists scaling($w,vscroll)] } {
        if { $scaling($w,current) >= 0.0 } {
            set scaling($w,theight) $scaling($w,ymax)
            $scaling($w,vscroll) set 0.0 1.0
        } else {
            set scaling($w,theight) [expr {$scaling($w,ymax)-$scaling($w,current)}]
            $scaling($w,vscroll) set $scaling($w,curpos) \
                [expr {$scaling($w,curpos) + $scaling($w,ymax)/$scaling($w,theight)}]
        }
    }

    if { [info exists scaling($w,hscroll)] } {
        foreach {xmin dummy xmax} [$w bbox $w horizscroll] {break}
        set scaling($w,twidth) [expr {$xmax-$xmin}]
        if { $scaling($w,twidth) < $scaling($w,pxmax)-$scaling($w,pxmin) } {
            $scaling($w,hscroll) set 0.0 1.0
        } else {
            $scaling($w,hscroll) set $scaling($w,curhpos) \
                [expr {$scaling($w,curhpos) + \
                         ($scaling($w,pxmax)-$scaling($w,pxmin)) \
                         /double($scaling($w,twidth))}]
        }
    }
}

# ConnectVertScrollbar --
#    Connect a vertical scroll bar to the chart
# Arguments:
#    w           Canvas widget containing them
#    scrollbar   Scroll bar in question
# Result:
#    None
#
proc ::Plotchart::ConnectVertScrollbar { w scrollbar } {
    variable scaling

    $scrollbar configure -command [list ::Plotchart::VertScrollChart $w]
    bind $w <4> [list ::Plotchart::VertScrollChart $w scroll  -1 units]
    bind $w <5> [list ::Plotchart::VertScrollChart $w scroll   1 units]
    bind $w <MouseWheel> [list ::Plotchart::VertScrollChart $w scroll %D wheel]
    set scaling($w,vscroll) $scrollbar

    RescaleChart $w
}

# ConnectHorizScrollbar --
#    Connect a horizontal scroll bar to the chart
# Arguments:
#    w           Canvas widget containing them
#    scrollbar   Scroll bar in question
# Result:
#    None
#
proc ::Plotchart::ConnectHorizScrollbar { w scrollbar } {
    variable scaling

    $scrollbar configure -command [list ::Plotchart::HorizScrollChart $w]
    set scaling($w,hscroll) $scrollbar

    RescaleChart $w
}

# VertScrollChart --
#    Scroll a chart using the vertical scroll bar
# Arguments:
#    w           Canvas widget containing them
#    operation   Operation to respond to
#    number      Number representing the size of the displacement
#    unit        Unit of displacement
# Result:
#    None
#
proc ::Plotchart::!VertScrollChart { w operation number {unit {}}} {
    variable scaling

    set pixheight [expr {$scaling($w,pymax)-$scaling($w,pymin)}]
    set height    [expr {$pixheight*$scaling($w,theight)/$scaling($w,ymax)}]

    switch -- $operation {
        "moveto" {
            set dy                 [expr {$height*($scaling($w,curpos)-$number)}]
            set scaling($w,curpos) $number
        }
        "scroll" {
            if { $unit == "units" } {
                set dy     [expr {-$number*$height/$scaling($w,theight)}]
                set newpos [expr {$scaling($w,curpos) + $number/$scaling($w,theight)}]
            } else {
                set dy     [expr {-$number*$pixheight}]
                set newpos [expr {$scaling($w,curpos) + $number*$scaling($w,ymax)/$scaling($w,theight)}]
            }

            # TODO: guard against scrolling too far
            #if { $newpos < 0.0 } {
            #    set newpos 0.0
            #    set dy     [expr {$...}]
            #}
            #
            #if { $newpos > 1.0 } {
            #    set newpos 1.0
            #    set dy     [expr {$...}]
            #}
            set scaling($w,curpos) $newpos
        }
    }

    #
    # TODO: limit the position between 0 and 1
    #

    $w move vertscroll 0 $dy

    RescaleChart $w
}
proc ::Plotchart::VertScrollChart { w operation number {unit {}}} {
    variable scaling

    # Get the height of the scrolling region and the current position of the slider
    set height [expr {$scaling($w,pymax)-$scaling($w,pymin)}]
    foreach {ts bs} [$scaling($w,vscroll) get] {break}

    if { $unit == "wheel" } {
        set operation "scroll"
        set unit      "units"
        set number    [expr {$number>0? 1 : -1}]
    }

    switch -- $operation {
        "moveto" {
            # No scrolling if we are already at the top or bottom
            if { $number < 0.0 } {
                set number 0.0
            }
            if { $number+($bs-$ts) > 1.0 } {
                set number [expr {1.0-($bs-$ts)}]
            }
            set dy     [expr {$height*($scaling($w,curpos)-$number)/($bs-$ts)}]
            set scaling($w,curpos) $number
            $w move vertscroll 0 $dy
        }
        "scroll" {
            # Handle "units" and "pages" the same

            # No scrolling if we are at the top or bottom
            if {$number == -1 && $ts == 0.0} {
                return
            }

            if {$number == 1 && $bs == 1.0} {
                return
            }

            # Scroll 1 unit in coordinate space, converted to pixel space
            foreach {x1 y1} [coordsToPixel $w 0 0.0] {break}
            foreach {x2 y2} [coordsToPixel $w 0 1.0] {break}

            # This is the amount to scroll based on the current height
            set amt [expr {$number*($y2-$y1)/$height}]

            # Handle boundary conditions, don't want to scroll too far off
            # the top or bottom.
            if {$number == 1 && $bs-$amt > 1.0} {
                set amt [expr {$bs-1.0}]
            } elseif {$number == -1 && $ts-$amt < 0.0} {
                set amt $ts
            }

            # Set the scrolling parameters and scroll
            set dy  [expr {$height*($scaling($w,curpos)-($ts-$amt))/($bs-$ts)}]
            set scaling($w,curpos) [expr {$ts-$amt}]
            $w move vertscroll 0 $dy
        }
    }

    RescaleChart $w
}

# HorizScrollChart --
#    Scroll a chart using the horizontal scroll bar
# Arguments:
#    w           Canvas widget containing them
#    operation   Operation to respond to
#    number      Number representing the size of the displacement
#    unit        Unit of displacement
# Result:
#    None
#
proc ::Plotchart::HorizScrollChart { w operation number {unit {}}} {
    variable scaling

    # Get the width of the scrolling region and the current position of the slider
    set width [expr {double($scaling($w,pxmax)-$scaling($w,pxmin))}]
    foreach {ts bs} [$scaling($w,hscroll) get] {break}

    switch -- $operation {
        "moveto" {
            # No scrolling if we are already at the top or bottom
            if { $number < 0.0 } {
                set number 0.0
            }
            if { $number+($bs-$ts) > 1.0 } {
                set number [expr {1.0-($bs-$ts)}]
            }
            set dx     [expr {$width*($scaling($w,curhpos)-$number)/($bs-$ts)}]
            set scaling($w,curhpos) $number
            $w move horizscroll $dx 0
        }
        "scroll" {
            # Handle "units" and "pages" the same

            # No scrolling if we are at the top or bottom
            if {$number == -1 && $ts == 0.0} {
                return
            }

            if {$number == 1 && $bs == 1.0} {
                return
            }

            # Scroll 1 unit in coordinate space, converted to pixel space
            set dx [expr {0.1*($scaling($w,xmax)-$scaling($w,xmin))}]
            foreach {x1 y1} [coordsToPixel $w 0   0.0] {break}
            foreach {x2 y2} [coordsToPixel $w $dx 0.0] {break}

            # This is the amount to scroll based on the current width
            set amt [expr {$number*($x2-$x1)/$width}]

            # Handle boundary conditions, don't want to scroll too far off
            # the left or the right
            if {$number == 1 && $bs-$amt > 1.0} {
                set amt [expr {$bs-1.0}]
            } elseif {$number == -1 && $ts-$amt < 0.0} {
                set amt $ts
            }

            # Set the scrolling parameters and scroll
            set dx  [expr {$width*($scaling($w,curhpos)-($ts-$amt))/($bs-$ts)}]
            set scaling($w,curhpos) [expr {$ts-$amt}]
            $w move horizscroll $dx 0
        }
    }

    RescaleChart $w
}

# DrawWindRoseData --
#    Draw the data for each sector
# Arguments:
#    w           Name of the canvas
#    data        List of "sectors" data
#    colour      Colour to use
# Result:
#    None
# Side effects:
#    Data added to the wind rose
#
proc ::Plotchart::DrawWindRoseData { w data colour } {

    variable data_series

    set start_angle  $data_series($w,start_angle)
    set increment    $data_series($w,increment_angle)
    set width_sector $data_series($w,d_angle)

    set new_cumulative {}

    foreach value $data cumulative_radius $data_series($w,cumulative_radius) {
        set radius [expr {$value + $cumulative_radius}]

        foreach {xright ytop}    [polarToPixel $w [expr {$radius*sqrt(2.0)}]  45.0] {break}
        foreach {xleft  ybottom} [polarToPixel $w [expr {$radius*sqrt(2.0)}] 225.0] {break}

        $w create arc $xleft $ytop $xright $ybottom -style pie -fill $colour \
            -tag [list $w data_$data_series($w,count_data)] -start $start_angle -extent $width_sector

        lappend new_cumulative $radius

        set start_angle [expr {$start_angle - $increment}]
    }

    $w lower [list data_$data_series($w,count_data) && $w]

    set data_series($w,cumulative_radius) $new_cumulative
    incr data_series($w,count_data)
}

# DrawYband --
#    Draw a vertical grey band in a plot
# Arguments:
#    w           Name of the canvas
#    xmin        Lower bound of the band
#    xmax        Upper bound of the band
# Result:
#    None
# Side effects:
#    Horizontal band drawn in canvas
#
proc ::Plotchart::DrawYband { w xmin xmax } {
    variable scaling


    foreach {xp1 yp1} [coordsToPixel $w $xmin $scaling($w,ymin)] {break}
    foreach {xp2 yp2} [coordsToPixel $w $xmax $scaling($w,ymax)] {break}

    $w create rectangle $xp1 $yp1 $xp2 $yp2 -fill grey70 -outline grey70 -tag [list band $w]

    $w lower [list band && $w] ;# TODO: also in "plot" method
}

# DrawXband --
#    Draw a horizontal grey band in a plot
# Arguments:
#    w           Name of the canvas
#    ymin        Lower bound of the band
#    ymax        Upper bound of the band
# Result:
#    None
# Side effects:
#    Horizontal band drawn in canvas
#
proc ::Plotchart::DrawXband { w ymin ymax } {
    variable scaling


    foreach {xp1 yp1} [coordsToPixel $w $scaling($w,xmin) $ymin] {break}
    foreach {xp2 yp2} [coordsToPixel $w $scaling($w,xmax) $ymax] {break}

    $w create rectangle $xp1 $yp1 $xp2 $yp2 -fill grey70 -outline grey70 -tag [list band $w]

    $w lower [list band $w] ;# TODO: also in "plot" method
}

# DrawLabelDot --
#    Draw a label and a symbol (dot) in a plot
# Arguments:
#    w           Name of the canvas
#    x           X coordinate of the dot
#    y           Y coordinate of the dot
#    text        Text to be shown
#    orient      (Optional) orientation of the text wrt the dot
#                (w, e, n, s)
#
# Result:
#    None
# Side effects:
#    Label and dot drawn in canvas
# Note:
#    The routine uses the data series name "labeldot" to derive
#    the properties
#
proc ::Plotchart::DrawLabelDot { w x y text {orient w} } {
    variable scaling

    foreach {xp yp} [coordsToPixel $w $x $y] {break}

    switch -- [string tolower $orient] {
        "w" {
            set xp [expr {$xp - 5}]
            set anchor e
        }
        "e" {
            set xp [expr {$xp + 10}]
            set anchor w
        }
        "s" {
            set yp [expr {$yp + 5}]
            set anchor n
        }
        "n" {
            set yp [expr {$yp - 5}]
            set anchor s
        }
        default {
            set xp [expr {$xp - 5}]
            set anchor w
        }
    }

    $w create text $xp $yp -text $text -fill grey -tag [list data $w] -anchor $anchor
    DrawData $w labeldot $x $y
}

# DrawLabelDotPolar --
#    Draw a label and a symbol (dot) in a polar plot
# Arguments:
#    w           Name of the canvas
#    rad         Radial coordinate of the dot
#    angle       Tangential coordinate of the dot
#    text        Text to be shown
#    orient      (Optional) orientation of the text wrt the dot
#                (w, e, n, s)
#
# Result:
#    None
# Side effects:
#    Label and dot drawn in canvas
# Note:
#    The routine uses the data series name "labeldot" to derive
#    the properties
#
proc ::Plotchart::DrawLabelDotPolar { w rad angle text {orient w} } {
    variable torad

    set xcrd [expr {$rad*cos($angle*$torad)}]
    set ycrd [expr {$rad*sin($angle*$torad)}]

    DrawLabelDot $w $xcrd $ycrd $text $orient
}

# ConfigBar --
#    Configuration options for vertical and horizontal barcharts
# Arguments:
#    w           Name of the canvas
#    args        List of arguments
# Result:
#    None
# Side effects:
#    Items that are already visible will NOT be changed to the new look
#
proc ::Plotchart::ConfigBar { w args } {
    variable settings

    foreach {option value} $args {
        set option [string range $option 1 end]
        if { [lsearch {showvalues valuefont valuecolour valuecolor valueformat} \
                $option] >= 0} {
            if { $option == "valuecolor" } {
                set option "valuecolour"
            }
            set settings($w,$option) $value
        } else {
            return -code error "Unknown barchart option: -$option"
        }
    }
}

# DrawFunction --
#    Draw a function f(x) in an XY-plot
# Arguments:
#    w           Name of the canvas
#    series      Data series (for the colour)
#    xargs       List of arguments to the (anonymous) function
#    function    Function expression
#    args        All parameters in the expression
#                (and possibly the option -samples x)
# Result:
#    None
# Side effects:
#    New data drawn in canvas
#
# Note:
#    This method requires Tcl 8.5
#
# TODO:
#    Check for numerical problems!
#
proc ::Plotchart::DrawFunction { w series xargs function args } {
   variable data_series
   variable scaling

   #
   # Check the number of arguments
   #
   if { [llength $xargs]     != [llength $args] + 1 &&
        [llength $xargs] + 2 != [llength $args] + 1 } {
       return -code error "plotfunc: number of (extra) arguments does not match the list of variables"
   }

   #
   # Determine the number of samples
   #
   set number 50
   if { [llength $xargs] + 2 == [llength $args] + 1 } {
       if { [lindex $args end-1] != "-samples" } {
           return -code error "plotfunc: unknown option - [lindex $args end-1]"
       }
       if { ! [string is integer [lindex $args end]] } {
           return -code error "plotfunc: number of samples must be an integer - is instead \"[lindex $args end]\""
       }
       set number [lindex $args end]
       set args   [lrange $args 0 end-2]
   }

   #
   # Get the caller's namespace
   #
   set namespace [uplevel 2 {namespace current}]

   #
   # The actual drawing
   #
   set colour black
   if { [info exists data_series($w,$series,-colour)] } {
      set colour $data_series($w,$series,-colour)
   }

   set width 1
   if { [info exists data_series($w,$series,-width)] } {
      set width $data_series($w,$series,-width)
   }

   set xmin   $scaling($w,xmin)
   set dx     [expr {($scaling($w,xmax) - $xmin) / ($number - 1.0)}]

   set coords {}
   set lambda [string map [list XARGS $xargs FUNCTION $function NS $namespace] {{XARGS} {expr {FUNCTION}} NS}]

   for { set i 0 } { $i < $number } { incr i } {
       set x [expr {$xmin + $dx*$i}]

       if { [catch {
           set y [apply $lambda $x {*}$args]

           foreach {pxcrd pycrd} [coordsToPixel $w $x $y] {break}

           lappend coords $pxcrd $pycrd
       } msg] } {
           if { [llength $coords] > 2 } {
               $w create line $coords -fill $colour -smooth 1 -width $width -tag [list data $w data_$series]
               set coords {}
           }
       }

   }
   if { [llength $coords] > 2 } {
       $w create line $coords -fill $colour -smooth 1 -width $width -tag [list data $w data_$series]
   }

   $w lower [list data && $w]
}

# ClearPlot --
#     Clear the current canvas and associated data
#     in order to be able to draw another plot
#     and re-using the same canvas
#
# Arguments:
#     w        Name of the canvas
#
# Results:
#     None
#
# Side effects:
#   all objects on the canvas will be deleted
#   and all associated data removed
#
proc ::Plotchart::ClearPlot {w} {
    variable data_series
    variable scaling

    foreach s [array names data_series "$w,*"] {
        unset data_series($s)
    }
    foreach s [array names scaling "$w,*"] {
        unset scaling($s)
    }
    #$w delete $w
}

# NewPlotInCanvas --
#     Determine the name for the new plot
#
# Arguments:
#     c  Name of the canvas
#
# Results:
#     Unique name for the plot
#
proc ::Plotchart::NewPlotInCanvas {c} {
    variable scaling

    if { ! [info exists scaling($c,plots)] } {
        set scaling($c,plots) 0
    } else {
        incr scaling($c,plots)
    }

    return [format "%02d%s" $scaling($c,plots) $c]
}

# DrawDataList --
#    Draw the data contained in two lists in an XY-plot
# Arguments:
#    w           Name of the canvas
#    series      Data series
#    xlist       List of x coordinates
#    ylist       List of y coordinates
#    every       Draw a symbol every N data
# Result:
#    None
# Side effects:
#    New data drawn in canvas
#
proc ::Plotchart::DrawDataList { w series xlist ylist {every {}} } {
    variable data_series
    variable scaling

    if { $every == {} } {
        set every [expr {int(sqrt([llength $xlist]))}]
        if { [llength $xlist] < 10 } {
            set every 1
        }
    }

    #
    # Determine the properties
    #
    set colour "black"
    if { [info exists data_series($w,$series,-colour)] } {
       set colour $data_series($w,$series,-colour)
    }

    set type "line"
    if { [info exists data_series($w,$series,-type)] } {
       set type $data_series($w,$series,-type)
    }
    set filled "no"
    if { [info exists data_series($w,$series,-filled)] } {
       set filled $data_series($w,$series,-filled)
    }
    set fillcolour white
    if { [info exists data_series($w,$series,-fillcolour)] } {
       set fillcolour $data_series($w,$series,-fillcolour)
    }
    set width 1
    if { [info exists data_series($w,$series,-width)] } {
       set width $data_series($w,$series,-width)
    }

    #
    # Draw all data
    # For the moment: no continuation!
    #
    if { [info exists data_series($w,$series,x)] } {
        set xold    $data_series($w,$series,x)
        set yold    $data_series($w,$series,y)

        set pcoords [coordsToPixel $w $xold $yold]

    } else {
        set xold    {}
        set yold    {}
        set pcoords {}
    }

    foreach xcrd $xlist ycrd $ylist {
        #
        # Check for missing values
        #
        if { $xcrd == "" || $ycrd == "" } {
            if { $pcoords != {} } {
                if { $type == "line" || $type == "both" } {
                    $w create line $pcoords \
                             -fill $colour -width $width -tag [list data $w data_$series]
                }
            }
            set pcoords {}
            continue
        } else {

            foreach {pxcrd pycrd} [coordsToPixel $w $xcrd $ycrd] {break}
            lappend pcoords $pxcrd $pycrd
        }
    }
    set data_series($w,$series,x) $xcrd
    set data_series($w,$series,y) $ycrd

    if { $pcoords != {} } {
        if { $type == "line" || $type == "both" } {
            $w create line $pcoords \
                     -fill $colour -width $width -tag [list data $w data_$series]
        }
    }

    if { $type == "symbol" || $type == "both" } {
        set symbol "dot"
        if { [info exists data_series($w,$series,-symbol)] } {
           set symbol $data_series($w,$series,-symbol)
        }
        for {set i 0} {$i < [llength $xlist]} {incr i $every} {
            set xcrd [lindex $xlist $i]
            set ycrd [lindex $ylist $i]

            if { $xcrd != {} && $ycrd != {} } {
                foreach {pxcrd pycrd} [coordsToPixel $w $xcrd $ycrd] {break}

                DrawSymbolPixel $w $series $pxcrd $pycrd $symbol $colour [list data $w data_$series]
            }
        }
    }

    $w lower [list data && $w]
}

# RenderText --
#    Draw the specified text into a plot using special rendering tags
# Arguments:
#    w           Name of the canvas
#    x           canvas x coordinate
#    y           canvas y coordinate
#    args        the text to render and additional text formatting information as option value pairs
# Result:
#    None
# Side effects:
#    Text String drawn in canvas
#
proc ::Plotchart::RenderText { w x y args } {
   variable render
   set render(poshoriz) $x
   set render(posvert) $y
   set render(items) [list]
   set render(superFont) {}
   set render(subFont) {}

   array set options {-font {} -text {} -fill {} -anchor c -tags {}}
   # specified options:
   array set options $args
   # options to actually use:
   array set newOptions $args
   array unset newOptions -text
   # use this -anchor for now, correct later:
   set newOptions(-anchor) sw

   # do the rendering:
   foreach {text tag} $options(-text) {
       lassign [RenderSpecs $tag $options(-font)] xp1 yp1 xp2 yp2 advance newFont
       set newOptions(-font) $newFont
       RenderTextDo $w $text $xp1 $yp1 $xp2 $yp2 $advance [array get newOptions]
   }

   # fix the -anchor for the whole string:
   set bbox [$w bbox {*}$render(items)]
   lassign $bbox bx1 by1 bx2 by2
   lassign {0 0} dx dy
   # dy:
   switch $options(-anchor) {
       n - nw - ne {
          set dy [expr {$by2 - $by1}]
       }
       w - e - c {
          set dy [expr {($by2 - $by1)/2.0}]
       }
   }
   # dx:
   switch $options(-anchor) {
       c - n - s {
          set dx [expr {($bx1-$bx2)/2.0}]
       }
       ne - e - se {
          set dx [expr {$bx1-$bx2}]
       }
   }
   foreach item $render(items) {$w move $item $dx $dy}
}

# renderSpecs --
#    Read a render tag and determine the position of the
#    associated text string
#
# Arguments:
#    tag    tag to get specifications for
#    font   font requested by the user
#
# Result:
#    List of specs with relative positions, advancing information, and the font to use
#
proc ::Plotchart::RenderSpecs {tag font} {
   variable render
   set advance 1
   set xp1     0 ;# how much to add to x coord before drawing
   set yp1     0 ;# how much to add to y coord before drawing
   set xp2     0 ;# how much to add to x coord afer drawing
   set yp2     0 ;# how much to add to y coord after drawing

   switch -- $tag {
       "_" { # Subscript
           if {$render(subFont) eq ""} {
               set render(subFont) [font create {*}[font configure $font]]
               set fontsize [font configure $font -size]
               set fontsize [expr {round($fontsize * 3.0/5.0)}]
               font configure $render(subFont) -size $fontsize
           } else {
               set fontsize [$render(subFont) configure -size]
           }
           set tmpFont $render(subFont)
           set yp1 [expr {round($fontsize/3.0)}]
           set yp2 [expr {-1 * $yp1}]
           set xp1 [expr {round($fontsize/-5.0)}]
           set xp2 [expr {round($fontsize/-5.0)}]
           set advance 1
        }
       "^" { # Superscript
             if {$render(subFont) eq ""} {
                 set render(superFont) [font create {*}[font configure $font]]
                 set fontsize [font configure $font -size]
                 set fontsize [expr {round($fontsize * 3.0/5.0)}]
                 font configure $render(superFont) -size $fontsize
             } else {
                 set fontsize [$render(superFont) configure -size]
             }
             set tmpFont $render(superFont)
             set yp1 [expr {round($fontsize/-1.5)}]
             set yp2 [expr {-1 * $yp1}]
             set xp1 [expr {round($fontsize/-5.0)}]
             set xp2 [expr {round($fontsize/-5.0)}]
             set advance 1
           }
       default {
           set tmpFont $font
       }
   }
   return [list $xp1 $yp1 $xp2 $yp2 $advance $tmpFont]
}

# doRender --
#    Render the given string according to the additional
#    rendering information
#
# Arguments:
#    canvas       Canvas in which to draw
#    string       text to be rendered
#    xp1          X-offset relative to current position before drawing
#    yp1          Y-offset relative to current position before drawing
#    xp2          X-offset after drawing
#    yp2          Y-offset after drawing
#    advance      whether we should advance to the next x position
#    fontOptions  list of pairs with formatting info for the font to use
#
# Result:
#    None
#
# Side effect:
#    The token is drawn on the canvas
#
proc ::Plotchart::RenderTextDo {canvas string xp1 yp1 xp2 yp2 advance fontOptions} {
   variable render

   # new coords where to start drawing text:
   set xpos [expr {$render(poshoriz)+$xp1}]
   set ypos [expr {$render(posvert)+$yp1}]

   set item [$canvas create text $xpos $ypos -text $string {*}$fontOptions]
   lappend render(items) $item
   set bbox [$canvas bbox $item]
   set width [expr {[lindex $bbox 2]-[lindex $bbox 0]}]
   set xpos [expr {$xpos+$width+$xp2}]
   set ypos [expr {$ypos+$yp2}]

   if {$advance} {
      set render(poshoriz) $xpos
      set render(posvert) $ypos
   }
}

# DeleteData --
#     Delete the data elements and the associated resources
#
# Arguments:
#     w          Name of the canvas (actually the plot)
#
# Result:
#     None
# Side effects:
#     The data elements in the canvas are removed and the
#     last known data points are removed from the resources.
#     However, the rest (legend, options for data series) is not.
#     This is deliberate: you may simply want to refresh the
#     data.
#
proc ::Plotchart::DeleteData {w} {
    variable data_series
    variable scaling

    foreach elem [array names data_series $w,*,x] {
         unset -nocomplain data_series($elem)
    }

    $w delete data
}