summaryrefslogtreecommitdiff
path: root/blt/src/bltGrAxis.c
blob: e9d4f2a30b34c0c017ec80a569e98101d9e9a73e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549

/*
 * bltGrAxis.c --
 *
 *	This module implements coordinate axes for the BLT graph widget.
 *
 * Copyright 1993-1998 Lucent Technologies, Inc.
 *
 * Permission to use, copy, modify, and distribute this software and
 * its documentation for any purpose and without fee is hereby
 * granted, provided that the above copyright notice appear in all
 * copies and that both that the copyright notice and warranty
 * disclaimer appear in supporting documentation, and that the names
 * of Lucent Technologies any of their entities not be used in
 * advertising or publicity pertaining to distribution of the software
 * without specific, written prior permission.
 *
 * Lucent Technologies disclaims all warranties with regard to this
 * software, including all implied warranties of merchantability and
 * fitness.  In no event shall Lucent Technologies be liable for any
 * special, indirect or consequential damages or any damages
 * whatsoever resulting from loss of use, data or profits, whether in
 * an action of contract, negligence or other tortuous action, arising
 * out of or in connection with the use or performance of this
 * software.
 */

#include "bltGraph.h"
#include "bltGrElem.h"
#include <X11/Xutil.h>

#define HIDE_ALL		-1

#define DEF_NUM_TICKS		4	/* Each minor tick is 20% */
#define STATIC_TICK_SPACE	10

#define TICK_LABEL_SIZE		200
#define MAXTICKS		10001

#define CLAMP(val,low,high)	\
	(((val) < (low)) ? (low) : ((val) > (high)) ? (high) : (val))

/*
 * Round x in terms of units
 */
#define UROUND(x,u)		(Round((x)/(u))*(u))
#define UCEIL(x,u)		(ceil((x)/(u))*(u))
#define UFLOOR(x,u)		(floor((x)/(u))*(u))

#define LENGTH_MAJOR_TICK 	0.030	/* Length of a major tick */
#define LENGTH_MINOR_TICK 	0.015	/* Length of a minor (sub)tick */
#define LENGTH_LABEL_TICK 	0.040	/* Distance from graph to start of the
					 * label */
#define NUMDIGITS		15	/* Specifies the number of
					 * digits of accuracy used when
					 * outputting axis tick labels. */
#define AVG_TICK_NUM_CHARS	16	/* Assumed average tick label size */

#define TICK_RANGE_TIGHT	0
#define TICK_RANGE_LOOSE	1
#define TICK_RANGE_ALWAYS_LOOSE	2

#define AXIS_TITLE_PAD		2	/* Padding for axis title. */
#define AXIS_LINE_PAD		1	/* Padding for axis line. */

#define HORIZMARGIN(m)	(!((m)->site & 0x1))	/* Even sites are horizontal */
/* Map graph coordinates to normalized coordinates [0..1] */
#define NORMALIZE(A,x) 	(((x) - (A)->tickRange.min) / (A)->tickRange.range)

typedef enum AxisComponents {
    MAJOR_TICK, MINOR_TICK, TICK_LABEL, AXIS_LINE
} AxisComponent;


typedef struct {
    int axis;		/* Length of the axis.  */
    int t1;		/* Length of a major tick (in pixels). */
    int t2;		/* Length of a minor tick (in pixels). */
    int label;		/* Distance from axis to tick label.  */
} AxisInfo;


extern Tk_CustomOption bltDistanceOption;
extern Tk_CustomOption bltPositiveDistanceOption;
extern Tk_CustomOption bltShadowOption;
extern Tk_CustomOption bltListOption;

static Tk_OptionParseProc StringToBounds;
static Tk_OptionPrintProc BoundsToString;
static Tk_OptionParseProc StringToTicks;
static Tk_OptionPrintProc TicksToString;
static Tk_OptionParseProc StringToAxis;
static Tk_OptionPrintProc AxisToString;
static Tk_OptionParseProc StringToAnyAxis;
static Tk_OptionParseProc StringToFormat;
static Tk_OptionPrintProc FormatToString;
static Tk_OptionParseProc StringToLoose;
static Tk_OptionPrintProc LooseToString;
static Tk_OptionParseProc StringToHide;
static Tk_OptionPrintProc HideToString;

static Tk_CustomOption minOption =
{
    StringToBounds, BoundsToString, (ClientData)AXIS_CONFIG_MIN,
};
static Tk_CustomOption maxOption =
{
    StringToBounds, BoundsToString, (ClientData)AXIS_CONFIG_MAX,
};
static Tk_CustomOption majorTicksOption =
{
    StringToTicks, TicksToString, (ClientData)AXIS_CONFIG_MAJOR,
};
static Tk_CustomOption minorTicksOption =
{
    StringToTicks, TicksToString, (ClientData)AXIS_CONFIG_MINOR,
};
Tk_CustomOption bltXAxisOption =
{
    StringToAxis, AxisToString, (ClientData)&bltXAxisUid
};
Tk_CustomOption bltYAxisOption =
{
    StringToAxis, AxisToString, (ClientData)&bltYAxisUid
};
Tk_CustomOption bltAnyXAxisOption =
{
    StringToAnyAxis, AxisToString, (ClientData)&bltXAxisUid
};
Tk_CustomOption bltAnyYAxisOption =
{
    StringToAnyAxis, AxisToString, (ClientData)&bltYAxisUid
};
static Tk_CustomOption formatOption =
{
    StringToFormat, FormatToString, (ClientData)0,
};
static Tk_CustomOption looseOption =
{
    StringToLoose, LooseToString, (ClientData)0,
};
static Tk_CustomOption hideOption =
{
    StringToHide, HideToString, (ClientData)0,
};

/* Axis flags: */

#define DEF_AXIS_ALT_HIDE		"no"
#define DEF_AXIS_COMMAND		(char *)NULL
#define DEF_AXIS_DESCENDING		"no"
#define DEF_AXIS_FG_COLOR		RGB_BLACK
#define DEF_AXIS_FG_MONO		RGB_BLACK
#define DEF_AXIS_HIDE			"no"
#define DEF_AXIS_HIDE_ALT		"no"
#define DEF_AXIS_HIDE_STD		"yes"
#define DEF_AXIS_JUSTIFY		"center"
#define DEF_AXIS_LIMITS_FORMAT	        (char *)NULL
#define DEF_AXIS_LINE_WIDTH		"1"
#define DEF_AXIS_LOGSCALE		"no"
#define DEF_AXIS_LOOSE			"no"
#define DEF_AXIS_MAJOR_TICKS		(char *)NULL
#define DEF_AXIS_MAX			(char *)NULL
#define DEF_AXIS_MIN			(char *)NULL
#define DEF_AXIS_RANGE			"0.0"
#define DEF_AXIS_ROTATE			"0.0"
#define DEF_AXIS_SCROLL_INCREMENT 	"10"
#define DEF_AXIS_SHADOW_COLOR		(char *)NULL
#define DEF_AXIS_SHADOW_MONO		(char *)NULL
#define DEF_AXIS_SHIFTBY		"0.0"
#define DEF_AXIS_SHOWTICKS		"yes"
#define DEF_AXIS_STEPSIZE		"0.0"
#define DEF_AXIS_SUBDIVISIONS		"2"
#define DEF_AXIS_TAGS			"all"
#define DEF_AXIS_TICKS			"0"
#ifdef WIN32
#define DEF_AXIS_TICK_FONT		"{Arial Narrow} 8"
#else
#define DEF_AXIS_TICK_FONT		"*-Helvetica-Medium-R-Normal-*-10-*"
#endif
#define DEF_AXIS_TICK_LENGTH		"8"
#define DEF_AXIS_TICK_VALUES		(char *)NULL
#define DEF_AXIS_TITLE			(char *)NULL
#define DEF_AXIS_TITLE_FG		RGB_BLACK
#define DEF_AXIS_TITLE_FONT		STD_FONT
#define DEF_AXIS_X_STEPSIZE_BARCHART	"1.0"
#define DEF_AXIS_X_SUBDIVISIONS_BARCHART "0"
#define DEF_AXIS_BACKGROUND		(char *)NULL
#define DEF_AXIS_BORDER_WIDTH		"0"
#define DEF_AXIS_RELIEF			"flat"

static Tk_ConfigSpec configSpecs[] =
{
    {TK_CONFIG_DOUBLE, "-autorange", "autoRange", "AutoRange",
	DEF_AXIS_RANGE, Tk_Offset(Axis, autoRange),
        ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT}, 
    {TK_CONFIG_BORDER, "-background", "background", "Background",
	DEF_AXIS_BACKGROUND, Tk_Offset(Axis, border),
	ALL_GRAPHS | TK_CONFIG_NULL_OK},
    {TK_CONFIG_SYNONYM, "-bg", "background", (char *)NULL, (char *)NULL, 0, 0},
    {TK_CONFIG_CUSTOM, "-bindtags", "bindTags", "BindTags",
	DEF_AXIS_TAGS, Tk_Offset(Axis, tags),
	ALL_GRAPHS | TK_CONFIG_NULL_OK, &bltListOption},
    {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *)NULL, 
        (char *)NULL, 0, ALL_GRAPHS},
    {TK_CONFIG_CUSTOM, "-borderwidth", "borderWidth", "BorderWidth",
	DEF_AXIS_BORDER_WIDTH, Tk_Offset(Axis, borderWidth),
	ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT, &bltDistanceOption},
    {TK_CONFIG_COLOR, "-color", "color", "Color",
	DEF_AXIS_FG_COLOR, Tk_Offset(Axis, tickStyle.color),
	TK_CONFIG_COLOR_ONLY | ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-color", "color", "Color",
	DEF_AXIS_FG_MONO, Tk_Offset(Axis, tickStyle.color),
	TK_CONFIG_MONO_ONLY | ALL_GRAPHS},
    {TK_CONFIG_STRING, "-command", "command", "Command",
	DEF_AXIS_COMMAND, Tk_Offset(Axis, formatCmd),
	TK_CONFIG_NULL_OK | ALL_GRAPHS},
    {TK_CONFIG_BOOLEAN, "-descending", "descending", "Descending",
	DEF_AXIS_DESCENDING, Tk_Offset(Axis, descending),
	ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-hide", "hide", "Hide",
	DEF_AXIS_HIDE, Tk_Offset(Axis, hidden),
	ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT, &hideOption},
    {TK_CONFIG_JUSTIFY, "-justify", "justify", "Justify",
	DEF_AXIS_JUSTIFY, Tk_Offset(Axis, titleStyle.justify),
	ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_COLOR, "-limitscolor", "limitsColor", "Color",
	DEF_AXIS_FG_COLOR, Tk_Offset(Axis, limitsStyle.color),
	TK_CONFIG_COLOR_ONLY | ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-limitscolor", "limitsColor", "Color",
	DEF_AXIS_FG_MONO, Tk_Offset(Axis, limitsStyle.color),
	TK_CONFIG_MONO_ONLY | ALL_GRAPHS},
    {TK_CONFIG_FONT, "-limitsfont", "limitsFont", "Font",
	DEF_AXIS_TICK_FONT, Tk_Offset(Axis, limitsStyle.font), ALL_GRAPHS},
    {TK_CONFIG_CUSTOM, "-limitsformat", "limitsFormat", "LimitsFormat",
	DEF_AXIS_LIMITS_FORMAT, Tk_Offset(Axis, limitsFormats),
	TK_CONFIG_NULL_OK | ALL_GRAPHS, &formatOption},
    {TK_CONFIG_CUSTOM, "-limitsshadow", "limitsShadow", "Shadow",
	DEF_AXIS_SHADOW_COLOR, Tk_Offset(Axis, limitsStyle.shadow),
	TK_CONFIG_COLOR_ONLY | ALL_GRAPHS, &bltShadowOption},
    {TK_CONFIG_CUSTOM, "-limitsshadow", "limitsShadow", "Shadow",
	DEF_AXIS_SHADOW_MONO, Tk_Offset(Axis, limitsStyle.shadow),
	TK_CONFIG_MONO_ONLY | ALL_GRAPHS, &bltShadowOption},
    {TK_CONFIG_CUSTOM, "-linewidth", "lineWidth", "LineWidth",
	DEF_AXIS_LINE_WIDTH, Tk_Offset(Axis, lineWidth),
	ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT, &bltDistanceOption},
    {TK_CONFIG_BOOLEAN, "-logscale", "logScale", "LogScale",
	DEF_AXIS_LOGSCALE, Tk_Offset(Axis, logScale),
	ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_CUSTOM, "-loose", "loose", "Loose",
	DEF_AXIS_LOOSE, 0, ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT,
	&looseOption},
    {TK_CONFIG_CUSTOM, "-majorticks", "majorTicks", "MajorTicks",
	DEF_AXIS_MAJOR_TICKS, Tk_Offset(Axis, t1Ptr),
	TK_CONFIG_NULL_OK | ALL_GRAPHS, &majorTicksOption},
    {TK_CONFIG_CUSTOM, "-max", "max", "Max",
	DEF_AXIS_MIN, 0, TK_CONFIG_NULL_OK | ALL_GRAPHS, &maxOption},
    {TK_CONFIG_CUSTOM, "-min", "min", "Min",
	DEF_AXIS_MAX, 0, TK_CONFIG_NULL_OK | ALL_GRAPHS, &minOption},
    {TK_CONFIG_CUSTOM, "-minorticks", "minorTicks", "MinorTicks",
	DEF_AXIS_TICK_VALUES, Tk_Offset(Axis, t2Ptr),
	TK_CONFIG_NULL_OK | ALL_GRAPHS, &minorTicksOption},
    {TK_CONFIG_RELIEF, "-relief", "relief", "Relief",
	DEF_AXIS_RELIEF, Tk_Offset(Axis, relief), 
        ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_DOUBLE, "-rotate", "rotate", "Rotate",
	DEF_AXIS_ROTATE, Tk_Offset(Axis, tickStyle.theta),
	ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_STRING, "-scrollcommand", "scrollCommand", "ScrollCommand",
	(char *)NULL, Tk_Offset(Axis, scrollCmdPrefix),
	ALL_GRAPHS | TK_CONFIG_NULL_OK},
    {TK_CONFIG_CUSTOM, "-scrollincrement", "scrollIncrement", "ScrollIncrement",
	DEF_AXIS_SCROLL_INCREMENT, Tk_Offset(Axis, scrollUnits),
	ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT, &bltPositiveDistanceOption},
    {TK_CONFIG_DOUBLE, "-shiftby", "shiftBy", "ShiftBy",
	DEF_AXIS_SHIFTBY, Tk_Offset(Axis, shiftBy),
	ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_BOOLEAN, "-showticks", "showTicks", "ShowTicks",
	DEF_AXIS_SHOWTICKS, Tk_Offset(Axis, showTicks),
	ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_DOUBLE, "-stepsize", "stepSize", "StepSize",
	DEF_AXIS_STEPSIZE, Tk_Offset(Axis, reqStep),
	ALL_GRAPHS | TK_CONFIG_DONT_SET_DEFAULT},
    {TK_CONFIG_INT, "-subdivisions", "subdivisions", "Subdivisions",
	DEF_AXIS_SUBDIVISIONS, Tk_Offset(Axis, reqNumMinorTicks),
	ALL_GRAPHS},
    {TK_CONFIG_FONT, "-tickfont", "tickFont", "Font",
	DEF_AXIS_TICK_FONT, Tk_Offset(Axis, tickStyle.font), ALL_GRAPHS},
    {TK_CONFIG_PIXELS, "-ticklength", "tickLength", "TickLength",
	DEF_AXIS_TICK_LENGTH, Tk_Offset(Axis, tickLength), ALL_GRAPHS},
    {TK_CONFIG_CUSTOM, "-tickshadow", "tickShadow", "Shadow",
	DEF_AXIS_SHADOW_COLOR, Tk_Offset(Axis, tickStyle.shadow),
	TK_CONFIG_COLOR_ONLY | ALL_GRAPHS, &bltShadowOption},
    {TK_CONFIG_CUSTOM, "-tickshadow", "tickShadow", "Shadow",
	DEF_AXIS_SHADOW_MONO, Tk_Offset(Axis, tickStyle.shadow),
	TK_CONFIG_MONO_ONLY | ALL_GRAPHS, &bltShadowOption},
    {TK_CONFIG_STRING, "-title", "title", "Title",
	DEF_AXIS_TITLE, Tk_Offset(Axis, titleText),
	TK_CONFIG_DONT_SET_DEFAULT | TK_CONFIG_NULL_OK | ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-titlecolor", "titleColor", "Color",
	DEF_AXIS_FG_COLOR, Tk_Offset(Axis, titleStyle.color),
	TK_CONFIG_COLOR_ONLY | ALL_GRAPHS},
    {TK_CONFIG_COLOR, "-titlecolor", "titleColor", "TitleColor",
	DEF_AXIS_FG_MONO, Tk_Offset(Axis, titleStyle.color),
	TK_CONFIG_MONO_ONLY | ALL_GRAPHS},
    {TK_CONFIG_FONT, "-titlefont", "titleFont", "Font",
	DEF_AXIS_TITLE_FONT, Tk_Offset(Axis, titleStyle.font), ALL_GRAPHS},
    {TK_CONFIG_CUSTOM, "-titleshadow", "titleShadow", "Shadow",
	DEF_AXIS_SHADOW_COLOR, Tk_Offset(Axis, titleStyle.shadow),
	TK_CONFIG_COLOR_ONLY | ALL_GRAPHS, &bltShadowOption},
    {TK_CONFIG_CUSTOM, "-titleshadow", "titleShadow", "Shadow",
	DEF_AXIS_SHADOW_MONO, Tk_Offset(Axis, titleStyle.shadow),
	TK_CONFIG_MONO_ONLY | ALL_GRAPHS, &bltShadowOption},
    {TK_CONFIG_END, NULL, NULL, NULL, NULL, 0, 0}
};

/* Forward declarations */
static void DestroyAxis _ANSI_ARGS_((Graph *graphPtr, Axis *axisPtr));
static int GetAxis _ANSI_ARGS_((Graph *graphPtr, char *name, Tk_Uid classUid,
	Axis **axisPtrPtr));
static void FreeAxis _ANSI_ARGS_((Graph *graphPtr, Axis *axisPtr));

INLINE static int
Round(x)
    register double x;
{
    return (int) (x + ((x < 0.0) ? -0.5 : 0.5));
}

INLINE static double
Fabs(x)
    register double x;
{
    return ((x < 0.0) ? -x : x);
}

/*
 * ----------------------------------------------------------------------
 *
 * InRange --
 *
 *	Determines if a value lies within a given range.
 *
 *	The value is normalized and compared against the interval
 *	[0..1], where 0.0 is the minimum and 1.0 is the maximum.
 *	DBL_EPSILON is the smallest number that can be represented
 *	on the host machine, such that (1.0 + epsilon) != 1.0.
 *
 *	Please note, *max* can't equal *min*.
 *
 * Results:
 *	If the value is within the interval [min..max], 1 is 
 *	returned; 0 otherwise.
 *
 * ----------------------------------------------------------------------
 */
INLINE static int
InRange(value, rangePtr)
    register double value;
    AxisRange *rangePtr;
{
    if (rangePtr->range < DBL_EPSILON) {
	return (FABS(rangePtr->max - value) >= DBL_EPSILON);
    } else {
	double norm;

	norm = (value - rangePtr->min) / rangePtr->range;
	return ((norm >= -DBL_EPSILON) && ((norm - 1.0) < DBL_EPSILON));
    }
}

INLINE static int
AxisIsHorizontal(graphPtr, axisPtr)
    Graph *graphPtr;
    Axis *axisPtr;
{
    return ((axisPtr->classUid == bltYAxisUid) == graphPtr->inverted);
}


/* ----------------------------------------------------------------------
 * Custom option parse and print procedures
 * ----------------------------------------------------------------------
 */

/*
 *----------------------------------------------------------------------
 *
 * StringToAnyAxis --
 *
 *	Converts the name of an axis to a pointer to its axis structure.
 *
 * Results:
 *	The return value is a standard Tcl result.  The axis flags are
 *	written into the widget record.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
StringToAnyAxis(clientData, interp, tkwin, string, widgRec, offset)
    ClientData clientData;	/* Class identifier of the type of 
				 * axis we are looking for. */
    Tcl_Interp *interp;		/* Interpreter to send results back to. */
    Tk_Window tkwin;		/* Used to look up pointer to graph. */
    char *string;		/* String representing new value. */
    char *widgRec;		/* Pointer to structure record. */
    int offset;			/* Offset of field in structure. */
{
    Axis **axisPtrPtr = (Axis **)(widgRec + offset);
    Tk_Uid classUid = *(Tk_Uid *)clientData;
    Graph *graphPtr;
    Axis *axisPtr;

    graphPtr = Blt_GetGraphFromWindowData(tkwin);
    if (*axisPtrPtr != NULL) {
	FreeAxis(graphPtr, *axisPtrPtr);
    }
    if (string[0] == '\0') {
	axisPtr = NULL;
    } else if (GetAxis(graphPtr, string, classUid, &axisPtr) != TCL_OK) {
	return TCL_ERROR;
    }
    *axisPtrPtr = axisPtr;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToAxis --
 *
 *	Converts the name of an axis to a pointer to its axis structure.
 *
 * Results:
 *	The return value is a standard Tcl result.  The axis flags are
 *	written into the widget record.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
StringToAxis(clientData, interp, tkwin, string, widgRec, offset)
    ClientData clientData;	/* Class identifier of the type of 
				 * axis we are looking for. */
    Tcl_Interp *interp;		/* Interpreter to send results back to. */
    Tk_Window tkwin;		/* Used to look up pointer to graph. */
    char *string;		/* String representing new value. */
    char *widgRec;		/* Pointer to structure record. */
    int offset;			/* Offset of field in structure. */
{
    Axis **axisPtrPtr = (Axis **)(widgRec + offset);
    Tk_Uid classUid = *(Tk_Uid *)clientData;
    Graph *graphPtr;

    graphPtr = Blt_GetGraphFromWindowData(tkwin);
    if (*axisPtrPtr != NULL) {
	FreeAxis(graphPtr, *axisPtrPtr);
    }
    if (GetAxis(graphPtr, string, classUid, axisPtrPtr) != TCL_OK) {
	return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * AxisToString --
 *
 *	Convert the window coordinates into a string.
 *
 * Results:
 *	The string representing the coordinate position is returned.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static char *
AxisToString(clientData, tkwin, widgRec, offset, freeProcPtr)
    ClientData clientData;	/* Not used. */
    Tk_Window tkwin;		/* Not used. */
    char *widgRec;		/* Pointer to structure record .*/
    int offset;			/* Offset of field in structure. */
    Tcl_FreeProc **freeProcPtr;	/* Not used. */
{
    Axis *axisPtr = *(Axis **)(widgRec + offset);

    if (axisPtr == NULL) {
	return "";
    }
    return axisPtr->name;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToFormat --
 *
 *	Convert the name of virtual axis to an pointer.
 *
 * Results:
 *	The return value is a standard Tcl result.  The axis flags are
 *	written into the widget record.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
StringToFormat(clientData, interp, tkwin, string, widgRec, offset)
    ClientData clientData;	/* Not used. */
    Tcl_Interp *interp;		/* Interpreter to send results back to. */
    Tk_Window tkwin;		/* Used to look up pointer to graph */
    char *string;		/* String representing new value. */
    char *widgRec;		/* Pointer to structure record. */
    int offset;			/* Offset of field in structure. */
{
    Axis *axisPtr = (Axis *)(widgRec);
    char **elemArr;
    int nElem;

    if (axisPtr->limitsFormats != NULL) {
	Blt_Free(axisPtr->limitsFormats);
    }
    axisPtr->limitsFormats = NULL;
    axisPtr->nFormats = 0;

    if ((string == NULL) || (*string == '\0')) {
	return TCL_OK;
    }
    if (Tcl_SplitList(interp, string, &nElem, &elemArr) != TCL_OK) {
	return TCL_ERROR;
    }
    if (nElem > 2) {
	Tcl_AppendResult(interp, "too many elements in limits format list \"",
	    string, "\"", (char *)NULL);
	Blt_Free(elemArr);
	return TCL_ERROR;
    }
    axisPtr->limitsFormats = elemArr;
    axisPtr->nFormats = nElem;
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * FormatToString --
 *
 *	Convert the window coordinates into a string.
 *
 * Results:
 *	The string representing the coordinate position is returned.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static char *
FormatToString(clientData, tkwin, widgRec, offset, freeProcPtr)
    ClientData clientData;	/* Not used. */
    Tk_Window tkwin;		/* Not used. */
    char *widgRec;		/* Widget record */
    int offset;			/* offset of limits field */
    Tcl_FreeProc **freeProcPtr;	/* Not used. */
{
    Axis *axisPtr = (Axis *)(widgRec);
    
    if (axisPtr->nFormats == 0) {
	return "";
    }
    *freeProcPtr = (Tcl_FreeProc *)Blt_Free;
    return Tcl_Merge(axisPtr->nFormats, axisPtr->limitsFormats); 
}

/*
 * ----------------------------------------------------------------------
 *
 * StringToBounds --
 *
 *	Convert the string representation of an axis limit into its numeric
 *	form.
 *
 * Results:
 *	The return value is a standard Tcl result.  The symbol type is
 *	written into the widget record.
 *
 * ----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
StringToBounds(clientData, interp, tkwin, string, widgRec, offset)
    ClientData clientData;	/* Either AXIS_CONFIG_MIN or AXIS_CONFIG_MAX.
				 * Indicates which axis limit to set. */
    Tcl_Interp *interp;		/* Interpreter to send results back to */
    Tk_Window tkwin;		/* Not used. */
    char *string;		/* String representing new value. */
    char *widgRec;		/* Pointer to structure record. */
    int offset;			/* Offset of field in structure. */
{
    Axis *axisPtr = (Axis *)(widgRec);
    unsigned int mask = (unsigned int)clientData;

    if ((string == NULL) || (*string == '\0')) {
	if (mask == AXIS_CONFIG_MIN) {
	    axisPtr->min = DBL_MAX;
	} else {
	    axisPtr->max = -DBL_MAX;
	}
	axisPtr->flags &= ~mask;
    } else {
	double value;

	if (Tcl_ExprDouble(interp, string, &value) != TCL_OK) {
	    return TCL_ERROR;
	}
	if (mask == AXIS_CONFIG_MIN) {
	    axisPtr->min = value;
	} else {
	    axisPtr->max = value;
	}
	axisPtr->flags |= mask;
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * BoundsToString --
 *
 *	Convert the floating point axis limits into a string.
 *
 * Results:
 *	The string representation of the limits is returned.
 *
 * ----------------------------------------------------------------------
 */
/*ARGSUSED*/
static char *
BoundsToString(clientData, tkwin, widgRec, offset, freeProcPtr)
    ClientData clientData;	/* Either LMIN or LMAX */
    Tk_Window tkwin;		/* Not used. */
    char *widgRec;		/* */
    int offset;
    Tcl_FreeProc **freeProcPtr;
{
    Axis *axisPtr = (Axis *)(widgRec);
    unsigned int mask = (unsigned int)clientData;
    char *result;

    result = "";
    if (axisPtr->flags & mask) {
	char string[TCL_DOUBLE_SPACE + 1];
	double value;
	Graph *graphPtr;

	graphPtr = Blt_GetGraphFromWindowData(tkwin);
	value = (mask == AXIS_CONFIG_MIN) ? axisPtr->min : axisPtr->max;
	Tcl_PrintDouble(graphPtr->interp, value, string);
	result = Blt_Strdup(string);
	if (result == NULL) {
	    return "";
	}
	*freeProcPtr = (Tcl_FreeProc *)Blt_Free;
    }
    return result;
}

/*
 * ----------------------------------------------------------------------
 *
 * StringToTicks --
 *
 *
 * Results:
 *
 * ----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
StringToTicks(clientData, interp, tkwin, string, widgRec, offset)
    ClientData clientData;	/* Not used. */
    Tcl_Interp *interp;		/* Interpreter to send results back to */
    Tk_Window tkwin;		/* Not used. */
    char *string;		/* String representing new value. */
    char *widgRec;		/* Pointer to structure record. */
    int offset;			/* Offset of field in structure. */
{
    unsigned int mask = (unsigned int)clientData;
    Axis *axisPtr = (Axis *)widgRec;
    Ticks **ticksPtrPtr = (Ticks **) (widgRec + offset);
    int nTicks;
    Ticks *ticksPtr;

    nTicks = 0;
    ticksPtr = NULL;
    if ((string != NULL) && (*string != '\0')) {
	int nExprs;
	char **exprArr;

	if (Tcl_SplitList(interp, string, &nExprs, &exprArr) != TCL_OK) {
	    return TCL_ERROR;
	}
	if (nExprs > 0) {
	    register int i;
	    int result = TCL_ERROR;
	    double value;

	    ticksPtr = Blt_Malloc(sizeof(Ticks) + (nExprs * sizeof(double)));
	    assert(ticksPtr);
	    for (i = 0; i < nExprs; i++) {
		result = Tcl_ExprDouble(interp, exprArr[i], &value);
		if (result != TCL_OK) {
		    break;
		}
		ticksPtr->tickArr[i] = value;
	    }
	    Blt_Free(exprArr);
	    if (result != TCL_OK) {
		Blt_Free(ticksPtr);
		return TCL_ERROR;
	    }
	    nTicks = nExprs;
	}
    }
    axisPtr->flags &= ~mask;
    if (ticksPtr != NULL) {
	axisPtr->flags |= mask;
	ticksPtr->nTicks = nTicks;
    }
    if (*ticksPtrPtr != NULL) {
	Blt_Free(*ticksPtrPtr);
    }
    *ticksPtrPtr = ticksPtr;
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * TicksToString --
 *
 *	Convert array of tick coordinates to a list.
 *
 * Results:
 *
 * ----------------------------------------------------------------------
 */
/*ARGSUSED*/
static char *
TicksToString(clientData, tkwin, widgRec, offset, freeProcPtr)
    ClientData clientData;	/* Not used. */
    Tk_Window tkwin;		/* Not used. */
    char *widgRec;		/* */
    int offset;
    Tcl_FreeProc **freeProcPtr;
{
    Ticks *ticksPtr = *(Ticks **) (widgRec + offset);
    char string[TCL_DOUBLE_SPACE + 1];
    register int i;
    char *result;
    Tcl_DString dString;
    Graph *graphPtr;

    if (ticksPtr == NULL) {
	return "";
    }
    Tcl_DStringInit(&dString);
    graphPtr = Blt_GetGraphFromWindowData(tkwin);
    for (i = 0; i < ticksPtr->nTicks; i++) {
	Tcl_PrintDouble(graphPtr->interp, ticksPtr->tickArr[i], string);
	Tcl_DStringAppendElement(&dString, string);
    }
    *freeProcPtr = (Tcl_FreeProc *)Blt_Free;
    result = Blt_Strdup(Tcl_DStringValue(&dString));
    Tcl_DStringFree(&dString);
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * StringToLoose --
 *
 *	Convert a string to one of three values.
 *		0 - false, no, off
 *		1 - true, yes, on
 *		2 - always
 * Results:
 *	If the string is successfully converted, TCL_OK is returned.
 *	Otherwise, TCL_ERROR is returned and an error message is left in
 *	interpreter's result field.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
StringToLoose(clientData, interp, tkwin, string, widgRec, offset)
    ClientData clientData;	/* Not used. */
    Tcl_Interp *interp;		/* Interpreter to send results back to */
    Tk_Window tkwin;		/* Not used. */
    char *string;		/* String representing new value. */
    char *widgRec;		/* Pointer to structure record. */
    int offset;			/* Offset of field in structure. */
{
    Axis *axisPtr = (Axis *)(widgRec);
    register int i;
    int nElems;
    char **elemArr;
    int values[2];

    if (Tcl_SplitList(interp, string, &nElems, &elemArr) != TCL_OK) {
	return TCL_ERROR;
    }
    if ((nElems < 1) || (nElems > 2)) {
	Tcl_AppendResult(interp, "wrong # elements in loose value \"",
	    string, "\"", (char *)NULL);
	return TCL_ERROR;
    }
    for (i = 0; i < nElems; i++) {
	if ((elemArr[i][0] == 'a') && (strcmp(elemArr[i], "always") == 0)) {
	    values[i] = TICK_RANGE_ALWAYS_LOOSE;
	} else {
	    int bool;

	    if (Tcl_GetBoolean(interp, elemArr[i], &bool) != TCL_OK) {
		Blt_Free(elemArr);
		return TCL_ERROR;
	    }
	    values[i] = bool;
	}
    }
    axisPtr->looseMin = axisPtr->looseMax = values[0];
    if (nElems > 1) {
	axisPtr->looseMax = values[1];
    }
    Blt_Free(elemArr);
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * LooseToString --
 *
 * Results:
 *	The string representation of the auto boolean is returned.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static char *
LooseToString(clientData, tkwin, widgRec, offset, freeProcPtr)
    ClientData clientData;	/* Not used. */
    Tk_Window tkwin;		/* Not used. */
    char *widgRec;		/* Widget record */
    int offset;			/* offset of flags field in record */
    Tcl_FreeProc **freeProcPtr;	/* Memory deallocation scheme to use */
{
    Axis *axisPtr = (Axis *)widgRec;
    Tcl_DString dString;
    char *result;

    Tcl_DStringInit(&dString);
    if (axisPtr->looseMin == TICK_RANGE_TIGHT) {
	Tcl_DStringAppendElement(&dString, "0");
    } else if (axisPtr->looseMin == TICK_RANGE_LOOSE) {
	Tcl_DStringAppendElement(&dString, "1");
    } else if (axisPtr->looseMin == TICK_RANGE_ALWAYS_LOOSE) {
	Tcl_DStringAppendElement(&dString, "always");
    }
    if (axisPtr->looseMin != axisPtr->looseMax) {
	if (axisPtr->looseMax == TICK_RANGE_TIGHT) {
	    Tcl_DStringAppendElement(&dString, "0");
	} else if (axisPtr->looseMax == TICK_RANGE_LOOSE) {
	    Tcl_DStringAppendElement(&dString, "1");
	} else if (axisPtr->looseMax == TICK_RANGE_ALWAYS_LOOSE) {
	    Tcl_DStringAppendElement(&dString, "always");
	}
    }
    result = Blt_Strdup(Tcl_DStringValue(&dString));
    Tcl_DStringFree(&dString);
    *freeProcPtr = (Tcl_FreeProc *)Blt_Free;
    return result;
}
/*
 *----------------------------------------------------------------------
 *
 * StringToHide --
 *
 *	Convert a string to one of three values.
 *		0 - false, no, off
 *		1 - true, yes, on
 *		2 - all
 * Results:
 *	If the string is successfully converted, TCL_OK is returned.
 *	Otherwise, TCL_ERROR is returned and an error message is left in
 *	interpreter's result field.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
StringToHide(clientData, interp, tkwin, string, widgRec, offset)
    ClientData clientData;	/* Not used. */
    Tcl_Interp *interp;		/* Interpreter to send results back to */
    Tk_Window tkwin;		/* Not used. */
    char *string;		/* String representation of new value. */
    char *widgRec;		/* Widget record */
    int offset;			/* Offset in the widget structure. */
{
    int *hidePtr = (int *)(widgRec + offset);

    if ((string[0] == 'a') && (strcmp(string, "all") == 0)) {
	*hidePtr = HIDE_ALL;
    } else {
	int bool;

	if (Tcl_GetBoolean(interp, string, &bool) != TCL_OK) {
	    return TCL_ERROR;
	}
	*hidePtr = bool;
    }
    return TCL_OK;
}

/*
 *----------------------------------------------------------------------
 *
 * HideToString --
 *
 * Results:
 *	The string representation of the button boolean is returned.
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static char *
HideToString(clientData, tkwin, widgRec, offset, freeProcPtr)
    ClientData clientData;	/* Not used. */
    Tk_Window tkwin;		/* Not used. */
    char *widgRec;		/* Widget record */
    int offset;			/* offset of flags field in record */
    Tcl_FreeProc **freeProcPtr;	/* Memory deallocation scheme to use */
{
    int hide = *(int *)(widgRec + offset);

    switch (hide) {
    case FALSE:
	return "0";
    case TRUE:
	return "1";
    case HIDE_ALL:
	return "all";
    default:
	return "unknown hide value";
    }
}


static void
FreeLabels(chainPtr)
    Blt_Chain *chainPtr;
{
    Blt_ChainLink *linkPtr;
    TickLabel *labelPtr;

    for (linkPtr = Blt_ChainFirstLink(chainPtr); linkPtr != NULL;
	 linkPtr = Blt_ChainNextLink(linkPtr)) {
	labelPtr = Blt_ChainGetValue(linkPtr);
	Blt_Free(labelPtr);
    }
    Blt_ChainReset(chainPtr);
}

/*
 * ----------------------------------------------------------------------
 *
 * MakeLabel --
 *
 *	Converts a floating point tick value to a string to be used as its
 *	label.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	Returns a new label in the string character buffer.  The formatted
 *	tick label will be displayed on the graph.
 *
 * ---------------------------------------------------------------------- 
 */
static TickLabel *
MakeLabel(graphPtr, axisPtr, value)
    Graph *graphPtr;
    Axis *axisPtr;		/* Axis structure */
    double value;		/* Value to be convert to a decimal string */
{
    char string[TICK_LABEL_SIZE + 1];
    TickLabel *labelPtr;

    /* Generate a default tick label based upon the tick value.  */
    if (axisPtr->logScale) {
	sprintf(string, "1E%d", ROUND(value));
    } else {
	sprintf(string, "%.*g", NUMDIGITS, value);
    }

    if (axisPtr->formatCmd != NULL) {
	Tcl_Interp *interp = graphPtr->interp;
	Tk_Window tkwin = graphPtr->tkwin;

	/*
	 * A Tcl proc was designated to format tick labels. Append the path
	 * name of the widget and the default tick label as arguments when
	 * invoking it. Copy and save the new label from interp->result.
	 */
	Tcl_ResetResult(interp);
	if (Tcl_VarEval(interp, axisPtr->formatCmd, " ", Tk_PathName(tkwin),
		" ", string, (char *)NULL) != TCL_OK) {
	    Tcl_BackgroundError(interp);
	} else {
	    /* 
	     * The proc could return a string of any length, so arbitrarily 
	     * limit it to what will fit in the return string. 
	     */
	    strncpy(string, Tcl_GetStringResult(interp), TICK_LABEL_SIZE);
	    string[TICK_LABEL_SIZE] = '\0';
	    
	    Tcl_ResetResult(interp); /* Clear the interpreter's result. */
	}
    }
    labelPtr = Blt_Malloc(sizeof(TickLabel) + strlen(string));
    assert(labelPtr);
    strcpy(labelPtr->string, string);
    labelPtr->anchorPos.x = labelPtr->anchorPos.y = DBL_MAX;
    return labelPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * InvHMap --
 *
 *	Maps the given screen coordinate back to a graph coordinate.
 *	Called by the graph locater routine.
 *
 * Results:
 *	Returns the graph coordinate value at the given window
 *	y-coordinate.
 *
 * ----------------------------------------------------------------------
 */
static double
InvHMap(graphPtr, axisPtr, x)
    Graph *graphPtr;
    Axis *axisPtr;
    double x;
{
    double norm, value;

    norm = (double)(x - graphPtr->hOffset) / (double)(graphPtr->hRange);
    if (axisPtr->descending) {
	norm = 1.0 - norm;
    }
    value = (norm * axisPtr->tickRange.range) + axisPtr->tickRange.min;
    if (axisPtr->logScale) {
	value = EXP10(value);
    }
    return value;
}

/*
 * ----------------------------------------------------------------------
 *
 * InvVMap --
 *
 *	Maps the given window y-coordinate back to a graph coordinate
 *	value. Called by the graph locater routine.
 *
 * Results:
 *	Returns the graph coordinate value at the given window
 *	y-coordinate.
 *
 * ----------------------------------------------------------------------
 */
static double
InvVMap(graphPtr, axisPtr, y)
    Graph *graphPtr;
    Axis *axisPtr;
    double y;
{
    double norm, value;

    norm = (double)(y - graphPtr->vOffset) / (double)graphPtr->vRange;
    if (axisPtr->descending) {
	norm = 1.0 - norm;
    }
    /* Note: This assumes that the tick range is as big or bigger than the
     * the range of data points. */
    value = ((1.0 - norm) * axisPtr->tickRange.range) + axisPtr->tickRange.min;
    if (axisPtr->logScale) {
	value = EXP10(value);
    }
    return value;
}

/*
 * ----------------------------------------------------------------------
 *
 * HMap --
 *
 *	Map the given graph coordinate value to its axis, returning a window
 *	position.
 *
 * Results:
 *	Returns a double precision number representing the window coordinate
 *	position on the given axis.
 *
 * ----------------------------------------------------------------------
 */
static double
HMap(graphPtr, axisPtr, x)
    Graph *graphPtr;
    Axis *axisPtr;
    double x;
{
    register double norm;

    if ((axisPtr->logScale) && (x != 0.0)) {
	x = log10(Fabs(x));
    }
    norm = NORMALIZE(axisPtr, x);
    if (axisPtr->descending) {
	norm = 1.0 - norm;
    }
    return ((norm * (graphPtr->hRange)) + graphPtr->hOffset);
}

/*
 * ----------------------------------------------------------------------
 *
 * VMap --
 *
 *	Map the given graph coordinate value to its axis, returning a window
 *	position.
 *
 * Results:
 *	Returns a double precision number representing the window coordinate
 *	position on the given axis.
 *
 * ----------------------------------------------------------------------
 */
static double
VMap(graphPtr, axisPtr, y)
    Graph *graphPtr;
    Axis *axisPtr;
    double y;
{
    register double norm;

    if ((axisPtr->logScale) && (y != 0.0)) {
	y = log10(Fabs(y));
    }
    norm = NORMALIZE(axisPtr, y);
    if (axisPtr->descending) {
	norm = 1.0 - norm;
    }
    return (((1.0 - norm) * (graphPtr->vRange)) + graphPtr->vOffset);
}

/*
 * ----------------------------------------------------------------------
 *
 * Blt_Map2D --
 *
 *	Maps the given graph x,y coordinate values to a window position.
 *
 * Results:
 *	Returns a XPoint structure containing the window coordinates of
 *	the given graph x,y coordinate.
 *
 * ----------------------------------------------------------------------
 */
Point2D
Blt_Map2D(graphPtr, x, y, axesPtr)
    Graph *graphPtr;
    double x, y;		/* Graph x and y coordinates */
    Axis2D *axesPtr;		/* Specifies which axes to use */
{
    Point2D point;

    if (graphPtr->inverted) {
	point.x = HMap(graphPtr, axesPtr->y, y);
	point.y = VMap(graphPtr, axesPtr->x, x);
    } else {
	point.x = HMap(graphPtr, axesPtr->x, x);
	point.y = VMap(graphPtr, axesPtr->y, y);
    }
    return point;
}

/*
 * ----------------------------------------------------------------------
 *
 * Blt_InvMap2D --
 *
 *	Maps the given window x,y coordinates to graph values.
 *
 * Results:
 *	Returns a structure containing the graph coordinates of
 *	the given window x,y coordinate.
 *
 * ----------------------------------------------------------------------
 */
Point2D
Blt_InvMap2D(graphPtr, x, y, axesPtr)
    Graph *graphPtr;
    double x, y;		/* Window x and y coordinates */
    Axis2D *axesPtr;		/* Specifies which axes to use */
{
    Point2D point;

    if (graphPtr->inverted) {
	point.x = InvVMap(graphPtr, axesPtr->x, y);
	point.y = InvHMap(graphPtr, axesPtr->y, x);
    } else {
	point.x = InvHMap(graphPtr, axesPtr->x, x);
	point.y = InvVMap(graphPtr, axesPtr->y, y);
    }
    return point;
}


static void
GetDataLimits(axisPtr, min, max)
    Axis *axisPtr;
    double min, max;
{
    if (axisPtr->dataRange.min > min) {
	axisPtr->dataRange.min = min;
    }
    if (axisPtr->dataRange.max < max) {
	axisPtr->dataRange.max = max;
    }
    axisPtr->flags |= AXIS_MAPS_ELEM;	/* Mark axis in use */
}

static void
FixAxisRange(axisPtr)
    Axis *axisPtr;
{
    /*
     * When auto-scaling, the axis limits are the bounds of the element
     * data.  If no data exists, set arbitrary limits (wrt to log/linear
     * scale).
     */
    if (axisPtr->dataRange.min == DBL_MAX) {
	axisPtr->dataRange.min = (axisPtr->logScale) ? 0.001 : 0.0;
    }
    if (axisPtr->dataRange.max == -DBL_MAX) {
	axisPtr->dataRange.max = 1.0;
    }
    if (axisPtr->dataRange.min >= axisPtr->dataRange.max) {
	double value;

	/*
	 * There is no range of data (i.e. min is not less than max), 
	 * so manufacture one.
	 */
	value = axisPtr->dataRange.min;
	if (value == 0.0) {
	    axisPtr->dataRange.min = -0.1, axisPtr->dataRange.max = 0.1;
	} else {
	    double x;

	    x = Fabs(value * 0.1);
	    axisPtr->dataRange.min = value - x;
	    axisPtr->dataRange.max = value + x;
	}
    }
    SetRange(axisPtr->dataRange);

    /*   
     * If the user hasn't already specified axis limits with the
     * -min or -max options, set the default axis limits to the be
     * current extents of the data.  
     */

    if (!(axisPtr->flags & AXIS_CONFIG_MIN)) {
	axisPtr->min = axisPtr->dataRange.min;
    }
    if (!(axisPtr->flags & AXIS_CONFIG_MAX)) {
	axisPtr->max = axisPtr->dataRange.max;
    }

    if (axisPtr->max < axisPtr->min) {

	/*   
	 * If the limits still don't make sense, it's because only
	 * one limit configuration option (-min or -max) was set and
	 * the other default (based upon the data) is too small/large.  
	 * Make up a new limit from the one that was set.  
	 */

	if (!(axisPtr->flags & AXIS_CONFIG_MIN)) {
	    axisPtr->min = axisPtr->max - (Fabs(axisPtr->max) * 0.1);
	}
	if (!(axisPtr->flags & AXIS_CONFIG_MAX)) {
	    axisPtr->max = axisPtr->min + (Fabs(axisPtr->max) * 0.1);
	}
    }
    /* Auto range */
    if ((axisPtr->autoRange > 0.0) && 
	((axisPtr->flags & (AXIS_CONFIG_MAX | AXIS_CONFIG_MIN)) == 0)) {
	double max;

	if (axisPtr->shiftBy < 0.0) {
	    axisPtr->shiftBy = 0.0;
	}
	max = axisPtr->min + axisPtr->autoRange;
	if (axisPtr->max >= max) {
	    if (axisPtr->shiftBy > 0.0) {
		max = UCEIL(axisPtr->max, axisPtr->shiftBy);
	    }
	    axisPtr->min = max - axisPtr->autoRange;
	}
	axisPtr->max = max;
    }
    if ((axisPtr->max != axisPtr->prevMax) ||
	(axisPtr->min != axisPtr->prevMin)) {
	/* Indicate if the axis limits have changed */
	axisPtr->flags |= AXIS_CONFIG_DIRTY;
	/* and save the previous minimum and maximum values */
	axisPtr->prevMin = axisPtr->min;
	axisPtr->prevMax = axisPtr->max;
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * NiceNum --
 *
 *	Reference: Paul Heckbert, "Nice Numbers for Graph Labels",
 *		   Graphics Gems, pp 61-63.  
 *
 *	Finds a "nice" number approximately equal to x.
 *
 * ----------------------------------------------------------------------
 */
static double
NiceNum(x, round)
    double x;
    int round;			/* If non-zero, round. Otherwise take ceiling
				 * of value. */
{
    double exponX;		/* exponent of x */
    double fractX;		/* fractional part of x */
    double nf;			/* nice, rounded fraction */

    exponX = floor(log10(x));
    fractX = x / EXP10(exponX);	/* between 1 and 10 */
    if (round) {
	if (fractX < 1.5) {
	    nf = 1.0;
	} else if (fractX < 3.0) {
	    nf = 2.0;
	} else if (fractX < 7.0) {
	    nf = 5.0;
	} else {
	    nf = 10.0;
	}
    } else if (fractX <= 1.0) {
	nf = 1.0;
    } else if (fractX <= 2.0) {
	nf = 2.0;
    } else if (fractX <= 5.0) {
	nf = 5.0;
    } else {
	nf = 10.0;
    }
    return nf * EXP10(exponX);
}

static Ticks *
GenerateTicks(sweepPtr)
    TickSweep *sweepPtr;
{
    Ticks *ticksPtr;
    register int i;
    double value;

    static double logTable[] =	/* Precomputed log10 values [1..10] */
    {
	0.0, 
	0.301029995663981, 0.477121254719662, 
	0.602059991327962, 0.698970004336019, 
	0.778151250383644, 0.845098040014257,
	0.903089986991944, 0.954242509439325, 
	1.0
    };
    ticksPtr = Blt_Malloc(sizeof(Ticks) + (sweepPtr->nSteps * sizeof(double)));
    assert(ticksPtr);
    value = sweepPtr->initial;	/* Start from smallest axis tick */

    if (sweepPtr->step == 0.0) { /* Hack: Zero step indicates to use
				  * log values */
	for (i = 0; i < sweepPtr->nSteps; i++) {
	    ticksPtr->tickArr[i] = logTable[i];
	}
    } else {
	for (i = 0; i < sweepPtr->nSteps; i++) {
	    value = UROUND(value, sweepPtr->step);
	    ticksPtr->tickArr[i] = value;
	    value += sweepPtr->step;
	}
    }
    ticksPtr->nTicks = sweepPtr->nSteps;
    return ticksPtr;
}

/*
 * ----------------------------------------------------------------------
 *
 * LogScaleAxis --
 *
 * 	Determine the range and units of a log scaled axis.
 *
 * 	Unless the axis limits are specified, the axis is scaled
 * 	automatically, where the smallest and largest major ticks encompass
 * 	the range of actual data values.  When an axis limit is specified,
 * 	that value represents the smallest(min)/largest(max) value in the
 * 	displayed range of values.
 *
 * 	Both manual and automatic scaling are affected by the step used.  By
 * 	default, the step is the largest power of ten to divide the range in
 * 	more than one piece.
 *
 *	Automatic scaling:
 *	Find the smallest number of units which contain the range of values.
 *	The minimum and maximum major tick values will be represent the
 *	range of values for the axis. This greatest number of major ticks
 *	possible is 10.
 *
 * 	Manual scaling:
 *   	Make the minimum and maximum data values the represent the range of
 *   	the values for the axis.  The minimum and maximum major ticks will be
 *   	inclusive of this range.  This provides the largest area for plotting
 *   	and the expected results when the axis min and max values have be set
 *   	by the user (.e.g zooming).  The maximum number of major ticks is 20.
 *
 *   	For log scale, there's the possibility that the minimum and
 *   	maximum data values are the same magnitude.  To represent the
 *   	points properly, at least one full decade should be shown.
 *   	However, if you zoom a log scale plot, the results should be
 *   	predictable. Therefore, in that case, show only minor ticks.
 *   	Lastly, there should be an appropriate way to handle numbers
 *   	<=0.
 *
 *          maxY
 *            |    units = magnitude (of least significant digit)
 *            |    high  = largest unit tick < max axis value
 *      high _|    low   = smallest unit tick > min axis value
 *            |
 *            |    range = high - low
 *            |    # ticks = greatest factor of range/units
 *           _|
 *        U   |
 *        n   |
 *        i   |
 *        t  _|
 *            |
 *            |
 *            |
 *       low _|
 *            |
 *            |_minX________________maxX__
 *            |   |       |      |       |
 *     minY  low                        high
 *           minY
 *
 *
 * 	numTicks = Number of ticks
 * 	min = Minimum value of axis
 * 	max = Maximum value of axis
 * 	range    = Range of values (max - min)
 *
 * 	If the number of decades is greater than ten, it is assumed
 *	that the full set of log-style ticks can't be drawn properly.
 *
 * Results:
 *	None
 *
 * ---------------------------------------------------------------------- */
static void
LogScaleAxis(axisPtr)
    Axis *axisPtr;
{
    double range;
    double min, max;
    double tickMin, tickMax;
    double stepMajor, stepMinor;
    int nMajor, nMinor;

    min = (axisPtr->min != 0.0) ? log10(Fabs(axisPtr->min)) : 0.0;
    max = (axisPtr->max != 0.0) ? log10(Fabs(axisPtr->max)) : 1.0;

    tickMin = floor(min);
    tickMax = ceil(max);
    range = tickMax - tickMin;

    if (range > 10) {
	/* There are too many decades to display a major tick at every
	 * decade.  Instead, treat the axis as a linear scale.  */
	range = NiceNum(range, 0);
	stepMajor = NiceNum(range / DEF_NUM_TICKS, 1);
	tickMin = UFLOOR(tickMin, stepMajor);
	tickMax = UCEIL(tickMax, stepMajor);
	nMajor = (int)((tickMax - tickMin) / stepMajor) + 1;
	stepMinor = EXP10(floor(log10(stepMajor)));
	if (stepMinor == stepMajor) {
	    nMinor = 4, stepMinor = 0.2;
	} else {
	    nMinor = Round(stepMajor / stepMinor) - 1;
	}
    } else {
	if (tickMin == tickMax) {
	    tickMax++;
	}
	stepMajor = 1.0;
	nMajor = (int)((tickMax - tickMin) + 1); /* FIXME: Check this. */

	stepMinor = 0.0;	/* This is a special hack to pass
				 * information to the GenerateTicks
				 * routine. An interval of 0.0 tells
				 *	1) this is a minor sweep and 
				 *	2) the axis is log scale.  
				 */
	nMinor = 10;
    }
    if ((axisPtr->looseMin == TICK_RANGE_TIGHT) ||
	((axisPtr->looseMin == TICK_RANGE_LOOSE) &&
	 (axisPtr->flags & AXIS_CONFIG_MIN))) {
	tickMin = min;
	nMajor++;
    }
    if ((axisPtr->looseMax == TICK_RANGE_TIGHT) ||
	((axisPtr->looseMax == TICK_RANGE_LOOSE) &&
	 (axisPtr->flags & AXIS_CONFIG_MAX))) {
	tickMax = max;
    }
    SetLimits(axisPtr->tickRange, tickMin, tickMax);

    axisPtr->majorSweep.step = stepMajor;
    axisPtr->majorSweep.initial = floor(tickMin);
    axisPtr->majorSweep.nSteps = nMajor;
    axisPtr->minorSweep.initial = axisPtr->minorSweep.step = stepMinor;
    axisPtr->minorSweep.nSteps = nMinor;
    
}

/*
 * ----------------------------------------------------------------------
 *
 * LinearScaleAxis --
 *
 * 	Determine the units of a linear scaled axis.
 *
 *	The axis limits are either the range of the data values mapped
 *	to the axis (autoscaled), or the values specified by the -min
 *	and -max options (manual).
 *
 *	If autoscaled, the smallest and largest major ticks will
 *	encompass the range of data values.  If the -loose option is
 *	selected, the next outer ticks are choosen.  If tight, the
 *	ticks are at or inside of the data limits are used.
 *
 * 	If manually set, the ticks are at or inside the data limits
 * 	are used.  This makes sense for zooming.  You want the
 * 	selected range to represent the next limit, not something a
 * 	bit bigger.
 *
 *	Note: I added an "always" value to the -loose option to force
 *	      the manually selected axes to be loose. It's probably
 *	      not a good idea.
 *
 *          maxY
 *            |    units = magnitude (of least significant digit)
 *            |    high  = largest unit tick < max axis value
 *      high _|    low   = smallest unit tick > min axis value
 *            |
 *            |    range = high - low
 *            |    # ticks = greatest factor of range/units
 *           _|
 *        U   |
 *        n   |
 *        i   |
 *        t  _|
 *            |
 *            |
 *            |
 *       low _|
 *            |
 *            |_minX________________maxX__
 *            |   |       |      |       |
 *     minY  low                        high
 *           minY
 *
 *
 * 	numTicks = Number of ticks
 * 	min = Minimum value of axis
 * 	max = Maximum value of axis
 * 	range    = Range of values (max - min)
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	The axis tick information is set.  The actual tick values will
 *	be generated later.
 *
 * ----------------------------------------------------------------------
 */
static void
LinearScaleAxis(axisPtr)
    Axis *axisPtr;
{
    double range;
    double min, max;
    double tickMin, tickMax;
    double stepMajor, stepMinor;
    int nMajor, nMinor;

    min = axisPtr->min;
    max = axisPtr->max;
    range = max - min;

    /* Calculate the major step.  If a step interval was designated,
     * use it only if it fits within the current range of the axis.  */
    if ((axisPtr->reqStep > 0.0) && (axisPtr->reqStep <= range) &&
	((int)(range / axisPtr->reqStep) <= MAXTICKS)) {
	stepMajor = axisPtr->reqStep;
    } else {
	range = NiceNum(range, 0);
	stepMajor = NiceNum(range / DEF_NUM_TICKS, 1);
    }

    /* Get the outer tick values. Add 0.0 to prevent getting an IEEE -0.0. */

    tickMin = UFLOOR(min, stepMajor) + 0.0;
    tickMax = UCEIL(max, stepMajor) + 0.0;
    nMajor = Round((tickMax - tickMin) / stepMajor) + 1;

    axisPtr->majorSweep.step = stepMajor;
    axisPtr->majorSweep.initial = tickMin;
    axisPtr->majorSweep.nSteps = nMajor;

    /*
     * The limits of the axis are either the range of the data
     * ("tight"), or at the next outer tick interval ("loose").  The
     * looseness or tightness has to do with how the axis fits the
     * range of data values.  This option is overridden when
     * the user sets an axis limit (by either -min or -max option).
     * The axis limit is always at the selected limit (otherwise we
     * assume that user would have picked a different number).
     */
    if ((axisPtr->looseMin == TICK_RANGE_TIGHT) ||
	((axisPtr->looseMin == TICK_RANGE_LOOSE) && 
	 (axisPtr->flags & AXIS_CONFIG_MIN))) {
	tickMin = min;
    }
    if ((axisPtr->looseMax == TICK_RANGE_TIGHT) ||
	((axisPtr->looseMax == TICK_RANGE_LOOSE) &&
	 (axisPtr->flags & AXIS_CONFIG_MAX))) {
	tickMax = max;
    }
    SetLimits(axisPtr->tickRange, tickMin, tickMax);

    /* Now calculate the minor tick step and number. */

    if ((axisPtr->reqNumMinorTicks > 0) && 
	((axisPtr->flags & AXIS_CONFIG_MAJOR) == 0)) {
	nMinor = axisPtr->reqNumMinorTicks - 1;
	stepMinor = 1.0 / (nMinor + 1);
    } else {
	nMinor = 0;		/* No minor ticks. */
	stepMinor = 0.5;	/* Don't set the minor tick interval
				 * to 0.0. It makes the GenerateTicks
				 * routine create minor log-scale tick
				 * marks.  */
    }
    axisPtr->minorSweep.initial = axisPtr->minorSweep.step = stepMinor;
    axisPtr->minorSweep.nSteps = nMinor;
}


static void
SweepTicks(axisPtr)
    Axis *axisPtr;
{
    if ((axisPtr->flags & AXIS_CONFIG_MAJOR) == 0) {
	if (axisPtr->t1Ptr != NULL) {
	    Blt_Free(axisPtr->t1Ptr);
	}
	axisPtr->t1Ptr = GenerateTicks(&(axisPtr->majorSweep));
    }
    if ((axisPtr->flags & AXIS_CONFIG_MINOR) == 0) {
	if (axisPtr->t2Ptr != NULL) {
	    Blt_Free(axisPtr->t2Ptr);
	}
	axisPtr->t2Ptr = GenerateTicks(&(axisPtr->minorSweep));
    }
}

/*
 * ----------------------------------------------------------------------
 *
 * Blt_ResetAxes --
 *
 * Results:
 *	None.
 *
 * ----------------------------------------------------------------------
 */
void
Blt_ResetAxes(graphPtr)
    Graph *graphPtr;
{
    Blt_ChainLink *linkPtr;
    Element *elemPtr;
    Axis *axisPtr;
    Blt_HashEntry *hPtr;
    Blt_HashSearch cursor;
    Extents2D exts;

    /* FIXME: This should be called whenever the display list of
     *	      elements change. Maybe yet another flag INIT_STACKS to
     *	      indicate that the element display list has changed.
     *	      Needs to be done before the axis limits are set.
     */
    Blt_InitFreqTable(graphPtr);
    if ((graphPtr->mode == MODE_STACKED) && (graphPtr->nStacks > 0)) {
	Blt_ComputeStacks(graphPtr);
    }
    /*
     * Step 1:  Reset all axes. Initialize the data limits of the axis to
     *		impossible values.
     */
    for (hPtr = Blt_FirstHashEntry(&(graphPtr->axes.table), &cursor);
	hPtr != NULL; hPtr = Blt_NextHashEntry(&cursor)) {
	axisPtr = (Axis *)Blt_GetHashValue(hPtr);
	axisPtr->flags &= ~AXIS_MAPS_ELEM;
	axisPtr->dataRange.min = DBL_MAX;
	axisPtr->dataRange.max = -DBL_MAX;
    }

    /*
     * Step 2:  For each element that's to be displayed, get the smallest
     *		and largest data values mapped to each X and Y-axis.  This
     *		will be the axis limits if the user doesn't override them 
     *		with -min and -max options.
     */
    for (linkPtr = Blt_ChainFirstLink(graphPtr->elements.chainPtr);
	linkPtr != NULL; linkPtr = Blt_ChainNextLink(linkPtr)) {
	elemPtr = Blt_ChainGetValue(linkPtr);
	if (!elemPtr->hidden) {
	    (*elemPtr->procsPtr->extentsProc) (elemPtr, &exts);
	    GetDataLimits(elemPtr->axes.x, exts.left, exts.right);
	    GetDataLimits(elemPtr->axes.y, exts.top, exts.bottom);
	}
    }
    /*
     * Step 3:  Now that we know the range of data values for each axis,
     *		set axis limits and compute a sweep to generate tick values.
     */
    for (hPtr = Blt_FirstHashEntry(&(graphPtr->axes.table), &cursor);
	hPtr != NULL; hPtr = Blt_NextHashEntry(&cursor)) {
	axisPtr = (Axis *)Blt_GetHashValue(hPtr);
	if (axisPtr->hidden == HIDE_ALL) {
	    continue;
	}
	FixAxisRange(axisPtr);
	/* Calculate min/max tick (major/minor) layouts */
	if (axisPtr->logScale) {
	    LogScaleAxis(axisPtr);
	} else {
	    LinearScaleAxis(axisPtr);
	}
	if (axisPtr->flags & AXIS_CONFIG_DIRTY) {
	    graphPtr->flags |= REDRAW_BACKING_STORE;
	}
    }

    graphPtr->flags &= ~RESET_AXES;

    /*
     * When any axis changes, we need to layout the entire graph.
     */
    graphPtr->flags |= (GET_AXIS_GEOMETRY | LAYOUT_NEEDED | 
			MAP_ALL | REDRAW_WORLD);
}

/*
 * ----------------------------------------------------------------------
 *
 * ResetTextStyles --
 *
 *	Configures axis attributes (font, line width, label, etc) and
 *	allocates a new (possibly shared) graphics context.  Line cap
 *	style is projecting.  This is for the problem of when a tick
 *	sits directly at the end point of the axis.
 *
 * Results:
 *	The return value is a standard Tcl result.
 *
 * Side Effects:
 *	Axis resources are allocated (GC, font). Axis layout is
 *	deferred until the height and width of the window are known.
 *
 * ----------------------------------------------------------------------
 */
static void
ResetTextStyles(graphPtr, axisPtr)
    Graph *graphPtr;
    Axis *axisPtr;
{
    GC newGC;
    XGCValues gcValues;
    unsigned long gcMask;

    Blt_ResetTextStyle(graphPtr->tkwin, &(axisPtr->titleStyle));
    Blt_ResetTextStyle(graphPtr->tkwin, &(axisPtr->tickStyle));
    Blt_ResetTextStyle(graphPtr->tkwin, &(axisPtr->limitsStyle));

    gcMask = (GCForeground | GCLineWidth | GCCapStyle);
    gcValues.foreground = axisPtr->tickStyle.color->pixel;
    gcValues.line_width = LineWidth(axisPtr->lineWidth);
    gcValues.cap_style = CapProjecting;

    newGC = Tk_GetGC(graphPtr->tkwin, gcMask, &gcValues);
    if (axisPtr->tickGC != NULL) {
	Tk_FreeGC(graphPtr->display, axisPtr->tickGC);
    }
    axisPtr->tickGC = newGC;
}

/*
 * ----------------------------------------------------------------------
 *
 * DestroyAxis --
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Resources (font, color, gc, labels, etc.) associated with the
 *	axis are deallocated.
 *
 * ----------------------------------------------------------------------
 */
static void
DestroyAxis(graphPtr, axisPtr)
    Graph *graphPtr;
    Axis *axisPtr;
{
    int flags;

    flags = Blt_GraphType(graphPtr);
    Tk_FreeOptions(configSpecs, (char *)axisPtr, graphPtr->display, flags);
    if (graphPtr->bindTable != NULL) {
	Blt_DeleteBindings(graphPtr->bindTable, axisPtr);
    }
    if (axisPtr->linkPtr != NULL) {
	Blt_ChainDeleteLink(axisPtr->chainPtr, axisPtr->linkPtr);
    }
    if (axisPtr->name != NULL) {
	Blt_Free(axisPtr->name);
    }
    if (axisPtr->hashPtr != NULL) {
	Blt_DeleteHashEntry(&(graphPtr->axes.table), axisPtr->hashPtr);
    }
    Blt_FreeTextStyle(graphPtr->display, &(axisPtr->titleStyle));
    Blt_FreeTextStyle(graphPtr->display, &(axisPtr->limitsStyle));
    Blt_FreeTextStyle(graphPtr->display, &(axisPtr->tickStyle));

    if (axisPtr->tickGC != NULL) {
	Tk_FreeGC(graphPtr->display, axisPtr->tickGC);
    }
    if (axisPtr->t1Ptr != NULL) {
	Blt_Free(axisPtr->t1Ptr);
    }
    if (axisPtr->t2Ptr != NULL) {
	Blt_Free(axisPtr->t2Ptr);
    }
    if (axisPtr->limitsFormats != NULL) {
	Blt_Free(axisPtr->limitsFormats);
    }
    FreeLabels(axisPtr->tickLabels);
    Blt_ChainDestroy(axisPtr->tickLabels);
    if (axisPtr->segments != NULL) {
	Blt_Free(axisPtr->segments);
    }
    if (axisPtr->tags != NULL) {
	Blt_Free(axisPtr->tags);
    }
    Blt_Free(axisPtr);
}

static double titleRotate[4] =	/* Rotation for each axis title */
{
    0.0, 90.0, 0.0, 270.0
};

/*
 * ----------------------------------------------------------------------
 *
 * AxisOffsets --
 *
 *	Determines the sites of the axis, major and minor ticks,
 *	and title of the axis.
 *
 * Results:
 *	None.
 *
 * ----------------------------------------------------------------------
 */
static void
AxisOffsets(graphPtr, axisPtr, margin, axisOffset, infoPtr)
    Graph *graphPtr;
    Axis *axisPtr;
    int margin;
    int axisOffset;
    AxisInfo *infoPtr;
{
    int pad;			/* Offset of axis from interior region. This
				 * includes a possible border and the axis
				 * line width. */
    int p;
    int majorOffset, minorOffset, labelOffset;
    int isMultiple;
    int offset;
    int x, y;

    isMultiple = (graphPtr->margins[margin].nAxes > 1);
    axisPtr->titleStyle.theta = titleRotate[margin];

    majorOffset = minorOffset = 0;
    labelOffset = AXIS_TITLE_PAD;
    if (axisPtr->lineWidth > 0) {
	majorOffset = ABS(axisPtr->tickLength);
	minorOffset = 10 * majorOffset / 15;
	labelOffset = majorOffset + AXIS_TITLE_PAD + axisPtr->lineWidth / 2;
    }
    /* Adjust offset for the interior border width and the line width */
    pad = axisPtr->lineWidth + 1;
    if (graphPtr->plotBW > 0) {
	pad += graphPtr->plotBW + 1;
    }
    offset = axisOffset + 1 + pad;
    if ((margin == MARGIN_LEFT) || (margin == MARGIN_TOP)) {
	majorOffset = -majorOffset;
	minorOffset = -minorOffset;
	labelOffset = -labelOffset;
    }
    /*
     * Pre-calculate the x-coordinate positions of the axis, tick labels, and
     * the individual major and minor ticks.
     */
    p = 0;		/* Suppress compiler warning */
    
    switch (margin) {
    case MARGIN_TOP:
	p = graphPtr->top - axisOffset - pad;
	if (isMultiple) {
	    x = graphPtr->right + AXIS_TITLE_PAD;
	    y = graphPtr->top - axisOffset - (axisPtr->height  / 2);
	    axisPtr->titleStyle.anchor = TK_ANCHOR_W;
	} else {
	    x = (graphPtr->right + graphPtr->left) / 2;
	    y = graphPtr->top - axisOffset - axisPtr->height - AXIS_TITLE_PAD;
	    axisPtr->titleStyle.anchor = TK_ANCHOR_N;
	}
	axisPtr->tickStyle.anchor = TK_ANCHOR_S;
	offset = axisPtr->borderWidth + axisPtr->lineWidth / 2;
	axisPtr->region.left = graphPtr->hOffset - offset - 2;
	axisPtr->region.right = graphPtr->hOffset + graphPtr->hRange + 
	    offset - 1;
	axisPtr->region.top = p + labelOffset - 1;
	axisPtr->region.bottom = p;
	axisPtr->titlePos.x = x;
	axisPtr->titlePos.y = y;
	break;

    case MARGIN_BOTTOM:
	p = graphPtr->bottom + axisOffset + pad;
	if (isMultiple) {
	    x = graphPtr->right + AXIS_TITLE_PAD;
	    y = graphPtr->bottom + axisOffset + (axisPtr->height / 2);
	    axisPtr->titleStyle.anchor = TK_ANCHOR_W; 
	} else {
	    x = (graphPtr->right + graphPtr->left) / 2;
	    y = graphPtr->bottom + axisOffset + axisPtr->height + 
		AXIS_TITLE_PAD;
	    axisPtr->titleStyle.anchor = TK_ANCHOR_S; 
	}
	axisPtr->tickStyle.anchor = TK_ANCHOR_N;
	offset = axisPtr->borderWidth + axisPtr->lineWidth / 2;
	axisPtr->region.left = graphPtr->hOffset - offset - 2;
	axisPtr->region.right = graphPtr->hOffset + graphPtr->hRange + 
	    offset - 1;

	axisPtr->region.top = graphPtr->bottom + axisOffset + 
	    axisPtr->lineWidth - axisPtr->lineWidth / 2;
	axisPtr->region.bottom = graphPtr->bottom + axisOffset + 
	    axisPtr->lineWidth + labelOffset + 1;
	axisPtr->titlePos.x = x;
	axisPtr->titlePos.y = y;
	break;

    case MARGIN_LEFT:
	p = graphPtr->left - axisOffset - pad;
	if (isMultiple) {
	    x = graphPtr->left - axisOffset - (axisPtr->width / 2);
	    y = graphPtr->top - AXIS_TITLE_PAD;
	    axisPtr->titleStyle.anchor = TK_ANCHOR_SW; 
	} else {
	    x = graphPtr->left - axisOffset - axisPtr->width -
		graphPtr->plotBW;
	    y = (graphPtr->bottom + graphPtr->top) / 2;
	    axisPtr->titleStyle.anchor = TK_ANCHOR_W; 
	}
	axisPtr->tickStyle.anchor = TK_ANCHOR_E;
	axisPtr->region.left = graphPtr->left - offset + labelOffset - 1;
	axisPtr->region.right = graphPtr->left - offset + 2;

	offset = axisPtr->borderWidth + axisPtr->lineWidth / 2;
	axisPtr->region.top = graphPtr->vOffset - offset - 2;
	axisPtr->region.bottom = graphPtr->vOffset + graphPtr->vRange + 
	    offset - 1;
	axisPtr->titlePos.x = x;
	axisPtr->titlePos.y = y;
	break;

    case MARGIN_RIGHT:
	p = graphPtr->right + axisOffset + pad;
	if (isMultiple) {
	    x = graphPtr->right + axisOffset + (axisPtr->width / 2);
	    y = graphPtr->top - AXIS_TITLE_PAD;
	    axisPtr->titleStyle.anchor = TK_ANCHOR_SE; 
	} else {
	    x = graphPtr->right + axisOffset + axisPtr->width + 
		AXIS_TITLE_PAD;
	    y = (graphPtr->bottom + graphPtr->top) / 2;
	    axisPtr->titleStyle.anchor = TK_ANCHOR_E;
	}
	axisPtr->tickStyle.anchor = TK_ANCHOR_W;

	axisPtr->region.left = graphPtr->right + axisOffset + 
	    axisPtr->lineWidth - axisPtr->lineWidth / 2;
	axisPtr->region.right = graphPtr->right + axisOffset + 
	    labelOffset + axisPtr->lineWidth + 1;

	offset = axisPtr->borderWidth + axisPtr->lineWidth / 2;
	axisPtr->region.top = graphPtr->vOffset - offset - 2;
	axisPtr->region.bottom = graphPtr->vOffset + graphPtr->vRange + 
	    offset - 1;
	axisPtr->titlePos.x = x;
	axisPtr->titlePos.y = y;
	break;

    case MARGIN_NONE:
	break;
    }
    infoPtr->axis = p - (axisPtr->lineWidth / 2);
    infoPtr->t1 = p + majorOffset;
    infoPtr->t2 = p + minorOffset;
    infoPtr->label = p + labelOffset;

    if (axisPtr->tickLength < 0) {
	int hold;
	
	hold = infoPtr->t1;
	infoPtr->t1 = infoPtr->axis;
	infoPtr->axis = hold;
    }
}

static void
MakeAxisLine(graphPtr, axisPtr, line, segPtr)
    Graph *graphPtr;
    Axis *axisPtr;		/* Axis information */
    int line;
    Segment2D *segPtr;
{
    double min, max;

    min = axisPtr->tickRange.min;
    max = axisPtr->tickRange.max;
    if (axisPtr->logScale) {
	min = EXP10(min);
	max = EXP10(max);
    }
    if (AxisIsHorizontal(graphPtr, axisPtr)) {
	segPtr->p.x = HMap(graphPtr, axisPtr, min);
	segPtr->q.x = HMap(graphPtr, axisPtr, max);
	segPtr->p.y = segPtr->q.y = line;
    } else {
	segPtr->q.x = segPtr->p.x = line;
	segPtr->p.y = VMap(graphPtr, axisPtr, min);
	segPtr->q.y = VMap(graphPtr, axisPtr, max);
    }
}


static void
MakeTick(graphPtr, axisPtr, value, tick, line, segPtr)
    Graph *graphPtr;
    Axis *axisPtr;
    double value;
    int tick, line;		/* Lengths of tick and axis line. */
    Segment2D *segPtr;
{
    if (axisPtr->logScale) {
	value = EXP10(value);
    }
    if (AxisIsHorizontal(graphPtr, axisPtr)) {
	segPtr->p.x = segPtr->q.x = HMap(graphPtr, axisPtr, value);
	segPtr->p.y = line;
	segPtr->q.y = tick;
    } else {
	segPtr->p.x = line;
	segPtr->p.y = segPtr->q.y = VMap(graphPtr, axisPtr, value);
	segPtr->q.x = tick;
    }
}

/*
 * -----------------------------------------------------------------
 *
 * MapAxis --
 *
 *	Pre-calculates positions of the axis, ticks, and labels (to be
 *	used later when displaying the axis).  Calculates the values
 *	for each major and minor tick and checks to see if they are in
 *	range (the outer ticks may be outside of the range of plotted
 *	values).
 *
 *	Line segments for the minor and major ticks are saved into one
 *	XSegment array so that they can be drawn by a single
 *	XDrawSegments call. The positions of the tick labels are also
 *	computed and saved.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	Line segments and tick labels are saved and used later to draw
 *	the axis.
 *
 * -----------------------------------------------------------------
 */
static void
MapAxis(graphPtr, axisPtr, offset, margin)
    Graph *graphPtr;
    Axis *axisPtr;
    int offset;
    int margin;
{
    int arraySize;
    int nMajorTicks, nMinorTicks;
    AxisInfo info;
    Segment2D *segments;
    Segment2D *segPtr;

    AxisOffsets(graphPtr, axisPtr, margin, offset, &info);

    /* Save all line coordinates in an array of line segments. */

    if (axisPtr->segments != NULL) {
	Blt_Free(axisPtr->segments);
    }
    nMajorTicks = nMinorTicks = 0;
    if (axisPtr->t1Ptr != NULL) {
	nMajorTicks = axisPtr->t1Ptr->nTicks;
    }
    if (axisPtr->t2Ptr != NULL) {
	nMinorTicks = axisPtr->t2Ptr->nTicks;
    }
    arraySize = 1 + (nMajorTicks * (nMinorTicks + 1));
    segments = Blt_Malloc(arraySize * sizeof(Segment2D));
    assert(segments);

    segPtr = segments;
    if (axisPtr->lineWidth > 0) {
	/* Axis baseline */
	MakeAxisLine(graphPtr, axisPtr, info.axis, segPtr);
	segPtr++;
    }
    if (axisPtr->showTicks) {
	double t1, t2;
	double labelPos;
	register int i, j;
	int isHoriz;
	TickLabel *labelPtr;
	Blt_ChainLink *linkPtr;

	isHoriz = AxisIsHorizontal(graphPtr, axisPtr);
	linkPtr = Blt_ChainFirstLink(axisPtr->tickLabels);
	for (i = 0; i < axisPtr->t1Ptr->nTicks; i++) {
	    t1 = axisPtr->t1Ptr->tickArr[i];
	    /* Minor ticks */
	    for (j = 0; j < axisPtr->t2Ptr->nTicks; j++) {
		t2 = t1 +
		    (axisPtr->majorSweep.step * axisPtr->t2Ptr->tickArr[j]);
		if (InRange(t2, &(axisPtr->tickRange))) {
		    MakeTick(graphPtr, axisPtr, t2, info.t2, info.axis, 
			     segPtr);
		    segPtr++;
		}
	    }
	    if (!InRange(t1, &(axisPtr->tickRange))) {
		continue;
	    }
	    /* Major tick and label position */
	    MakeTick(graphPtr, axisPtr, t1, info.t1, info.axis, segPtr);
	    labelPos = (double)info.label;

	    labelPtr = Blt_ChainGetValue(linkPtr);
	    linkPtr = Blt_ChainNextLink(linkPtr);

	    /* Save tick label X-Y position. */
	    if (isHoriz) {
		labelPtr->anchorPos.x = segPtr->p.x;
		labelPtr->anchorPos.y = labelPos;
	    } else {
		labelPtr->anchorPos.x = labelPos;
		labelPtr->anchorPos.y = segPtr->p.y;
	    }
	    segPtr++;
	}
    }
    if (AxisIsHorizontal(graphPtr, axisPtr)) {
	axisPtr->width = graphPtr->right - graphPtr->left;
    } else {
	axisPtr->height = graphPtr->bottom - graphPtr->top;
    }
    axisPtr->segments = segments;
    axisPtr->nSegments = segPtr - segments;
    assert(axisPtr->nSegments <= arraySize);
}

/*
 *----------------------------------------------------------------------
 *
 * AdjustViewport --
 *
 *	Adjusts the offsets of the viewport according to the scroll mode.
 *	This is to accommodate both "listbox" and "canvas" style scrolling.
 *
 *	"canvas"	The viewport scrolls within the range of world
 *			coordinates.  This way the viewport always displays
 *			a full page of the world.  If the world is smaller
 *			than the viewport, then (bizarrely) the world and
 *			viewport are inverted so that the world moves up
 *			and down within the viewport.
 *
 *	"listbox"	The viewport can scroll beyond the range of world
 *			coordinates.  Every entry can be displayed at the
 *			top of the viewport.  This also means that the
 *			scrollbar thumb weirdly shrinks as the last entry
 *			is scrolled upward.
 *
 * Results:
 *	The corrected offset is returned.
 *
 *----------------------------------------------------------------------
 */
static double
AdjustViewport(offset, windowSize)
    double offset, windowSize;
{
    /*
     * Canvas-style scrolling allows the world to be scrolled
     * within the window.
     */
    if (windowSize > 1.0) {
	if (windowSize < (1.0 - offset)) {
	    offset = 1.0 - windowSize;
	}
	if (offset > 0.0) {
	    offset = 0.0;
	}
    } else {
	if ((offset + windowSize) > 1.0) {
	    offset = 1.0 - windowSize;
	}
	if (offset < 0.0) {
	    offset = 0.0;
	}
    }
    return offset;
}

static int
GetAxisScrollInfo(interp, argc, argv, offsetPtr, windowSize, scrollUnits)
    Tcl_Interp *interp;
    int argc;
    char **argv;
    double *offsetPtr;
    double windowSize;
    double scrollUnits;
{
    char c;
    unsigned int length;
    double offset;
    int count;
    double fract;

    offset = *offsetPtr;
    c = argv[0][0];
    length = strlen(argv[0]);
    if ((c == 's') && (strncmp(argv[0], "scroll", length) == 0)) {
	assert(argc == 3);
	/* scroll number unit/page */
	if (Tcl_GetInt(interp, argv[1], &count) != TCL_OK) {
	    return TCL_ERROR;
	}
	c = argv[2][0];
	length = strlen(argv[2]);
	if ((c == 'u') && (strncmp(argv[2], "units", length) == 0)) {
	    fract = (double)count * scrollUnits;
	} else if ((c == 'p') && (strncmp(argv[2], "pages", length) == 0)) {
	    /* A page is 90% of the view-able window. */
	    fract = (double)count * windowSize * 0.9;
	} else {
	    Tcl_AppendResult(interp, "unknown \"scroll\" units \"", argv[2],
		"\"", (char *)NULL);
	    return TCL_ERROR;
	}
	offset += fract;
    } else if ((c == 'm') && (strncmp(argv[0], "moveto", length) == 0)) {
	assert(argc == 2);
	/* moveto fraction */
	if (Tcl_GetDouble(interp, argv[1], &fract) != TCL_OK) {
	    return TCL_ERROR;
	}
	offset = fract;
    } else {
	/* Treat like "scroll units" */
	if (Tcl_GetInt(interp, argv[0], &count) != TCL_OK) {
	    return TCL_ERROR;
	}
	fract = (double)count * scrollUnits;
	offset += fract;
	return TCL_OK;
    }
    *offsetPtr = AdjustViewport(offset, windowSize);
    return TCL_OK;
}

/*
 * -----------------------------------------------------------------
 *
 * DrawAxis --
 *
 *	Draws the axis, ticks, and labels onto the canvas.
 *
 *	Initializes and passes text attribute information through
 *	TextStyle structure.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	Axis gets drawn on window.
 *
 * -----------------------------------------------------------------
 */
static void
DrawAxis(graphPtr, drawable, axisPtr)
    Graph *graphPtr;
    Drawable drawable;
    Axis *axisPtr;
{
    if (axisPtr->border != NULL) {
	Tk_Fill3DRectangle(graphPtr->tkwin, drawable, axisPtr->border,
			   axisPtr->region.left + graphPtr->plotBW, 
			   axisPtr->region.top + graphPtr->plotBW, 
			   axisPtr->region.right - axisPtr->region.left, 
			   axisPtr->region.bottom - axisPtr->region.top, 
			   axisPtr->borderWidth, axisPtr->relief);
    }
    if (axisPtr->titleText != NULL) {
	Blt_DrawText(graphPtr->tkwin, drawable, axisPtr->titleText,
	    &(axisPtr->titleStyle), (int)axisPtr->titlePos.x, 
		     (int)axisPtr->titlePos.y);
    }
    if (axisPtr->scrollCmdPrefix != NULL) {
	double viewWidth, viewMin, viewMax;
	double worldWidth, worldMin, worldMax;
	double fract;
	int isHoriz;

	worldMin = axisPtr->dataRange.min;
	worldMax = axisPtr->dataRange.max;
	viewMin = axisPtr->min;
	viewMax = axisPtr->max;
	if (axisPtr->logScale) {
	    worldMin = log10(worldMin);
	    worldMax = log10(worldMax);
	    viewMin = log10(viewMin);
	    viewMax = log10(viewMax);
	}
	worldWidth = worldMax - worldMin;	
	viewWidth = viewMax - viewMin;
	isHoriz = AxisIsHorizontal(graphPtr, axisPtr);

	if (isHoriz != axisPtr->descending) {
	    fract = (viewMin - worldMin) / worldWidth;
	} else {
	    fract = (worldMax - viewMax) / worldWidth;
	}
	fract = AdjustViewport(fract, viewWidth / worldWidth);

	if (isHoriz != axisPtr->descending) {
	    viewMin = (fract * worldWidth);
	    axisPtr->min = viewMin + worldMin;
	    axisPtr->max = axisPtr->min + viewWidth;
	    viewMax = viewMin + viewWidth;
	    if (axisPtr->logScale) {
		axisPtr->min = EXP10(axisPtr->min);
		axisPtr->max = EXP10(axisPtr->max);
	    }
	    Blt_UpdateScrollbar(graphPtr->interp, axisPtr->scrollCmdPrefix,
		(viewMin / worldWidth), (viewMax / worldWidth));
	} else {
	    viewMax = (fract * worldWidth);
	    axisPtr->max = worldMax - viewMax;
	    axisPtr->min = axisPtr->max - viewWidth;
	    viewMin = viewMax + viewWidth;
	    if (axisPtr->logScale) {
		axisPtr->min = EXP10(axisPtr->min);
		axisPtr->max = EXP10(axisPtr->max);
	    }
	    Blt_UpdateScrollbar(graphPtr->interp, axisPtr->scrollCmdPrefix,
		(viewMax / worldWidth), (viewMin / worldWidth));
	}
    }
    if (axisPtr->showTicks) {
	register Blt_ChainLink *linkPtr;
	TickLabel *labelPtr;

	for (linkPtr = Blt_ChainFirstLink(axisPtr->tickLabels); linkPtr != NULL;
	    linkPtr = Blt_ChainNextLink(linkPtr)) {	
	    /* Draw major tick labels */
	    labelPtr = Blt_ChainGetValue(linkPtr);
	    Blt_DrawText(graphPtr->tkwin, drawable, labelPtr->string,
		&(axisPtr->tickStyle), (int)labelPtr->anchorPos.x, 
		(int)labelPtr->anchorPos.y);
	}
    }
    if ((axisPtr->nSegments > 0) && (axisPtr->lineWidth > 0)) {	
	/* Draw the tick marks and axis line. */
	Blt_DrawSegments2D(graphPtr->display, drawable, axisPtr->tickGC,
	    axisPtr->segments, axisPtr->nSegments);
    }
}

/*
 * -----------------------------------------------------------------
 *
 * AxisToPostScript --
 *
 *	Generates PostScript output to draw the axis, ticks, and
 *	labels.
 *
 *	Initializes and passes text attribute information through
 *	TextStyle structure.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	PostScript output is left in graphPtr->interp->result;
 *
 * -----------------------------------------------------------------
 */
/* ARGSUSED */
static void
AxisToPostScript(psToken, axisPtr)
    PsToken psToken;
    Axis *axisPtr;
{
    if (axisPtr->titleText != NULL) {
	Blt_TextToPostScript(psToken, axisPtr->titleText, 
	     &(axisPtr->titleStyle), axisPtr->titlePos.x, axisPtr->titlePos.y);
    }
    if (axisPtr->showTicks) {
	register Blt_ChainLink *linkPtr;
	TickLabel *labelPtr;

	for (linkPtr = Blt_ChainFirstLink(axisPtr->tickLabels); 
	     linkPtr != NULL; linkPtr = Blt_ChainNextLink(linkPtr)) {
	    labelPtr = Blt_ChainGetValue(linkPtr);
	    Blt_TextToPostScript(psToken, labelPtr->string, 
		 &(axisPtr->tickStyle), labelPtr->anchorPos.x, 
		labelPtr->anchorPos.y);
	}
    }
    if ((axisPtr->nSegments > 0) && (axisPtr->lineWidth > 0)) {
	Blt_LineAttributesToPostScript(psToken, axisPtr->tickStyle.color,
	    axisPtr->lineWidth, (Blt_Dashes *)NULL, CapButt, JoinMiter);
	Blt_Segments2DToPostScript(psToken, axisPtr->segments, 
	   axisPtr->nSegments);
    }
}

static void
MakeGridLine(graphPtr, axisPtr, value, segPtr)
    Graph *graphPtr;
    Axis *axisPtr;
    double value;
    Segment2D *segPtr;
{
    if (axisPtr->logScale) {
	value = EXP10(value);
    }
    /* Grid lines run orthogonally to the axis */
    if (AxisIsHorizontal(graphPtr, axisPtr)) {
	segPtr->p.y = graphPtr->top;
	segPtr->q.y = graphPtr->bottom;
	segPtr->p.x = segPtr->q.x = HMap(graphPtr, axisPtr, value);
    } else {
	segPtr->p.x = graphPtr->left;
	segPtr->q.x = graphPtr->right;
	segPtr->p.y = segPtr->q.y = VMap(graphPtr, axisPtr, value);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * Blt_GetAxisSegments --
 *
 *	Assembles the grid lines associated with an axis. Generates
 *	tick positions if necessary (this happens when the axis is
 *	not a logical axis too).
 *
 * Results:
 *	None.
 *
 *----------------------------------------------------------------------
 */
void
Blt_GetAxisSegments(graphPtr, axisPtr, segPtrPtr, nSegmentsPtr)
    Graph *graphPtr;
    Axis *axisPtr;
    Segment2D **segPtrPtr;
    int *nSegmentsPtr;
{
    int needed;
    Ticks *t1Ptr, *t2Ptr;
    register int i;
    double value;
    Segment2D *segments, *segPtr;

    *nSegmentsPtr = 0;
    *segPtrPtr = NULL;
    if (axisPtr == NULL) {
	return;
    }
    t1Ptr = axisPtr->t1Ptr;
    if (t1Ptr == NULL) {
	t1Ptr = GenerateTicks(&(axisPtr->majorSweep));
    }
    t2Ptr = axisPtr->t2Ptr;
    if (t2Ptr == NULL) {
	t2Ptr = GenerateTicks(&(axisPtr->minorSweep));
    }

    needed = t1Ptr->nTicks;
    if (graphPtr->gridPtr->minorGrid) {
	needed += (t1Ptr->nTicks * t2Ptr->nTicks);
    }
    if (needed == 0) {
	return;			
    }
    segments = Blt_Malloc(sizeof(Segment2D) * needed);
    if (segments == NULL) {
	return;			/* Can't allocate memory for grid. */
    }

    segPtr = segments;
    for (i = 0; i < t1Ptr->nTicks; i++) {
	value = t1Ptr->tickArr[i];
	if (graphPtr->gridPtr->minorGrid) {
	    register int j;
	    double subValue;

	    for (j = 0; j < t2Ptr->nTicks; j++) {
		subValue = value +
		    (axisPtr->majorSweep.step * t2Ptr->tickArr[j]);
		if (InRange(subValue, &(axisPtr->tickRange))) {
		    MakeGridLine(graphPtr, axisPtr, subValue, segPtr);
		    segPtr++;
		}
	    }
	}
	if (InRange(value, &(axisPtr->tickRange))) {
	    MakeGridLine(graphPtr, axisPtr, value, segPtr);
	    segPtr++;
	}
    }

    if (t1Ptr != axisPtr->t1Ptr) {
	Blt_Free(t1Ptr);	/* Free generated ticks. */
    }
    if (t2Ptr != axisPtr->t2Ptr) {
	Blt_Free(t2Ptr);	/* Free generated ticks. */
    }
    *nSegmentsPtr = segPtr - segments;
    assert(*nSegmentsPtr <= needed);
    *segPtrPtr = segments;
}

/*
 *----------------------------------------------------------------------
 *
 * GetAxisGeometry --
 *
 * Results:
 *	None.
 *
 *----------------------------------------------------------------------
 */
static void
GetAxisGeometry(graphPtr, axisPtr, isMultiple)
    Graph *graphPtr;
    Axis *axisPtr;
    int isMultiple;
{
    int height;

    FreeLabels(axisPtr->tickLabels);
    height = 0;
    if (axisPtr->lineWidth > 0) {
	/* Leave room for axis baseline (and pad) */
	height += axisPtr->lineWidth + 2;
    }
    if (axisPtr->showTicks) {
	int pad;
	register int i, nLabels;
	int labelWidth, labelHeight;
	double x;
	int maxWidth, maxHeight;
	TickLabel *labelPtr;

	SweepTicks(axisPtr);
	
	/* Hey Sani, does this check fail under AIX? */
	assert((axisPtr->t1Ptr->nTicks >= 0) && 
	       (axisPtr->t1Ptr->nTicks <= MAXTICKS));
	
	maxHeight = maxWidth = 0;
	nLabels = 0;
	for (i = 0; i < axisPtr->t1Ptr->nTicks; i++) {
	    x = axisPtr->t1Ptr->tickArr[i];
	    if (!InRange(x, &(axisPtr->tickRange))) {
		continue;
	    }
	    labelPtr = MakeLabel(graphPtr, axisPtr, x);
	    Blt_ChainAppend(axisPtr->tickLabels, labelPtr);
	    nLabels++;
	    
	    /* Get dimensions of each tick label.  Remember tick labels
	     * can be multi-lined and/or rotated. */
	    Blt_GetTextExtents(&(axisPtr->tickStyle), labelPtr->string, 
		       &labelWidth, &labelHeight);
	    labelPtr->width = labelWidth;
	    labelPtr->height = labelHeight;
	    if (axisPtr->tickStyle.theta > 0.0) {
		Blt_GetBoundingBox(labelWidth, labelHeight, 
			axisPtr->tickStyle.theta, &labelWidth, &labelHeight, 
			(Point2D *)NULL);
	    }
	    if (maxWidth < labelWidth) {
		maxWidth = labelWidth;
	    }
	    if (maxHeight < labelHeight) {
		maxHeight = labelHeight;
	    }
	}
	assert(nLabels <= axisPtr->t1Ptr->nTicks);
	
	/* Because the axis cap style is "CapProjecting", there's
	 * an extra 1.5 linewidth to be accounted for at the ends
	 * of each line.  */

	pad = ((axisPtr->lineWidth * 15) / 10);
	
	if (AxisIsHorizontal(graphPtr, axisPtr)) {
	    height += maxHeight + pad;
	} else {
	    height += maxWidth + pad;
	}
	if (axisPtr->lineWidth > 0) {
	    /* Distance from axis line to tick label. */
	    height += AXIS_TITLE_PAD;
	    height += ABS(axisPtr->tickLength);
	}
    }

    if (axisPtr->titleText != NULL) {
	if (isMultiple) {
	    if (height < axisPtr->titleHeight) {
		height = axisPtr->titleHeight;
	    }
	} else {
	    height += axisPtr->titleHeight + AXIS_TITLE_PAD;
	}
    }

    /* Correct for orientation of the axis. */
    if (AxisIsHorizontal(graphPtr, axisPtr)) {
	axisPtr->height = height;
    } else {
	axisPtr->width = height;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * GetMarginGeometry --
 *
 *	Examines all the axes in the given margin and determines the 
 *	area required to display them.  
 *
 *	Note: For multiple axes, the titles are displayed in another
 *	      margin. So we must keep track of the widest title.
 *	
 * Results:
 *	Returns the width or height of the margin, depending if it
 *	runs horizontally along the graph or vertically.
 *
 * Side Effects:
 *	The area width and height set in the margin.  Note again that
 *	this may be corrected later (mulitple axes) to adjust for
 *	the longest title in another margin.
 *
 *----------------------------------------------------------------------
 */
static int
GetMarginGeometry(graphPtr, marginPtr)
    Graph *graphPtr;
    Margin *marginPtr;
{
    Blt_ChainLink *linkPtr;
    Axis *axisPtr;
    int width, height;
    int isHoriz;
    int length, count;

    /* Count the number of visible axes. */
    count = 0;
    isHoriz = HORIZMARGIN(marginPtr);
    for (linkPtr = Blt_ChainFirstLink(marginPtr->chainPtr); linkPtr != NULL;
	 linkPtr = Blt_ChainNextLink(linkPtr)) {
	axisPtr = Blt_ChainGetValue(linkPtr);
	if (!axisPtr->hidden) {
	    count++;
	}
    }
    length = width = height = 0;
    for (linkPtr = Blt_ChainFirstLink(marginPtr->chainPtr); linkPtr != NULL;
	 linkPtr = Blt_ChainNextLink(linkPtr)) {
	axisPtr = Blt_ChainGetValue(linkPtr);
	if (axisPtr->hidden) {
	    continue;
	}
	if (graphPtr->flags & GET_AXIS_GEOMETRY) {
	    GetAxisGeometry(graphPtr, axisPtr, (count > 1));
	}
	if (length < axisPtr->titleWidth) {
	    length = axisPtr->titleWidth;
	}
	if (isHoriz) {
	    height += axisPtr->height;
	} else {
	    width += axisPtr->width;
	}
    }
    /* Enforce a minimum size for margins. */
    if (width < 3) {
	width = 3;
    }
    if (height < 3) {
	height = 3;
    }
    marginPtr->nAxes = count;
    marginPtr->axesTitleLength = length;
    marginPtr->width = width;
    marginPtr->height = height;
    marginPtr->axesOffset = (HORIZMARGIN(marginPtr)) ? height : width;
    return marginPtr->axesOffset;
}

/*
 *----------------------------------------------------------------------
 *
 * ComputeMargins --
 *
 *	Computes the size of the margins and the plotting area.  We
 *	first compute the space needed for the axes in each margin.
 *	Then how much space the legend will occupy.  Finally, if the
 *	user has requested a margin size, we override the computed
 *	value.
 *
 * Results:
 *
 *---------------------------------------------------------------------- */
static void
ComputeMargins(graphPtr)
    Graph *graphPtr;
{
    int left, right, top, bottom;
    int width, height;
    int insets;

    /* 
     * Step 1:	Compute the amount of space needed to display the
     *		axes (there many be 0 or more) associated with the
     *		margin.
     */
    top = GetMarginGeometry(graphPtr, &(graphPtr->topMargin));
    bottom = GetMarginGeometry(graphPtr, &(graphPtr->bottomMargin));
    left = GetMarginGeometry(graphPtr, &(graphPtr->leftMargin));
    right = GetMarginGeometry(graphPtr, &(graphPtr->rightMargin));

    /* 
     * Step 2:  Add the graph title height to the top margin. 
     */
    if (graphPtr->titleText != NULL) {
	top += graphPtr->titleStyle.height;
    }
    insets = 2 * (graphPtr->inset + graphPtr->plotBW);

    /* 
     * Step 3:  Use the current estimate of the plot area to compute 
     *		the legend size.  Add it to the proper margin.
     */
    width = graphPtr->width - (insets + left + right);
    height = graphPtr->height - (insets + top + bottom);
    Blt_MapLegend(graphPtr->legend, width, height);
    if (!Blt_LegendIsHidden(graphPtr->legend)) {
	switch (Blt_LegendSite(graphPtr->legend)) {
	case LEGEND_RIGHT:
	    right += Blt_LegendWidth(graphPtr->legend) + 2;
	    break;
	case LEGEND_LEFT:
	    left += Blt_LegendWidth(graphPtr->legend) + 2;
	    break;
	case LEGEND_TOP:
	    top += Blt_LegendHeight(graphPtr->legend) + 2;
	    break;
	case LEGEND_BOTTOM:
	    bottom += Blt_LegendHeight(graphPtr->legend) + 2;
	    break;
	case LEGEND_XY:
	case LEGEND_PLOT:
	case LEGEND_WINDOW:
	    /* Do nothing. */
	    break;
	}
    }

    /* 
     * Recompute the plotarea, now accounting for the legend. 
     */
    width = graphPtr->width - (insets + left + right);
    height = graphPtr->height - (insets + top + bottom);

    /*
     * Step 5:	If necessary, correct for the requested plot area 
     *		aspect ratio.
     */
    if (graphPtr->aspect > 0.0) {
	double ratio;

	/* 
	 * Shrink one dimension of the plotarea to fit the requested
	 * width/height aspect ratio.  
	 */
	ratio = (double)width / (double)height;
	if (ratio > graphPtr->aspect) {
	    int scaledWidth;

	    /* Shrink the width. */
	    scaledWidth = (int)(height * graphPtr->aspect);
	    if (scaledWidth < 1) {
		scaledWidth = 1;
	    }
	    right += (width - scaledWidth); /* Add the difference to
					     * the right margin. */
	    width = scaledWidth;
	} else {
	    int scaledHeight;

	    /* Shrink the height. */
	    scaledHeight = (int)(width / graphPtr->aspect);
	    if (scaledHeight < 1) {
		scaledHeight = 1;
	    }
	    top += (height - scaledHeight); /* Add the difference to
					    * the top margin. */
	    height = scaledHeight;
	}
    }

    /* 
     * Step 6:	If there's multiple axes in a margin, the axis 
     *		titles will be displayed in the adjoining marging.
     *		Make sure there's room for the longest axis titles. 
     */

    if ((graphPtr->leftMargin.nAxes > 1) && 
	(top < graphPtr->leftMargin.axesTitleLength)) {
	top = graphPtr->leftMargin.axesTitleLength;
    }
    if ((graphPtr->bottomMargin.nAxes > 1) && 
	(right < graphPtr->bottomMargin.axesTitleLength)) {
	right = graphPtr->bottomMargin.axesTitleLength;
    }
    if ((graphPtr->rightMargin.nAxes > 1) && 
	(top < graphPtr->rightMargin.axesTitleLength)) {
	top = graphPtr->rightMargin.axesTitleLength;
    }
    if ((graphPtr->topMargin.nAxes > 1) && 
	(right < graphPtr->topMargin.axesTitleLength)) {
	right = graphPtr->topMargin.axesTitleLength;
    }

    /* 
     * Step 7:  Override calculated values with requested margin 
     *		sizes. 
     */

    graphPtr->leftMargin.width = left;
    graphPtr->rightMargin.width = right;
    graphPtr->topMargin.height =  top;
    graphPtr->bottomMargin.height = bottom;

    if (graphPtr->leftMargin.reqSize > 0) {
	graphPtr->leftMargin.width = graphPtr->leftMargin.reqSize;
    }
    if (graphPtr->rightMargin.reqSize > 0) {
	graphPtr->rightMargin.width = graphPtr->rightMargin.reqSize;
    }
    if (graphPtr->topMargin.reqSize > 0) {
	graphPtr->topMargin.height = graphPtr->topMargin.reqSize;
    }
    if (graphPtr->bottomMargin.reqSize > 0) {
	graphPtr->bottomMargin.height = graphPtr->bottomMargin.reqSize;
    }
}

/*
 * -----------------------------------------------------------------
 *
 * Blt_LayoutMargins --
 *
 * 	Calculate the layout of the graph.  Based upon the data,
 *	axis limits, X and Y titles, and title height, determine
 *	the cavity left which is the plotting surface.  The first
 *	step get the data and axis limits for calculating the space
 *	needed for the top, bottom, left, and right margins.
 *
 * 	1) The LEFT margin is the area from the left border to the
 *	   Y axis (not including ticks). It composes the border
 *	   width, the width an optional Y axis label and its padding,
 *	   and the tick numeric labels. The Y axis label is rotated
 *	   90 degrees so that the width is the font height.
 *
 * 	2) The RIGHT margin is the area from the end of the graph
 *	   to the right window border. It composes the border width,
 *	   some padding, the font height (this may be dubious. It
 *	   appears to provide a more even border), the max of the
 *	   legend width and 1/2 max X tick number. This last part is
 *	   so that the last tick label is not clipped.
 *
 *           Window Width
 *      ___________________________________________________________
 *      |          |                               |               |
 *      |          |   TOP  height of title        |               |
 *      |          |                               |               |
 *      |          |           x2 title            |               |
 *      |          |                               |               |
 *      |          |        height of x2-axis      |               |
 *      |__________|_______________________________|_______________|  W
 *      |          | -plotpady                     |               |  i
 *      |__________|_______________________________|_______________|  n
 *      |          | top                   right   |               |  d
 *      |          |                               |               |  o
 *      |   LEFT   |                               |     RIGHT     |  w
 *      |          |                               |               |
 *      | y        |     Free area = 104%          |      y2       |  H
 *      |          |     Plotting surface = 100%   |               |  e
 *      | t        |     Tick length = 2 + 2%      |      t        |  i
 *      | i        |                               |      i        |  g
 *      | t        |                               |      t  legend|  h
 *      | l        |                               |      l   width|  t
 *      | e        |                               |      e        |
 *      |    height|                               |height         |
 *      |       of |                               | of            |
 *      |    y-axis|                               |y2-axis        |
 *      |          |                               |               |
 *      |          |origin 0,0                     |               |
 *      |__________|_left___________________bottom___|_______________|
 *      |          |-plotpady                      |               |
 *      |__________|_______________________________|_______________|
 *      |          | (xoffset, yoffset)            |               |
 *      |          |                               |               |
 *      |          |       height of x-axis        |               |
 *      |          |                               |               |
 *      |          |   BOTTOM   x title            |               |
 *      |__________|_______________________________|_______________|
 *
 * 3) The TOP margin is the area from the top window border to the top
 *    of the graph. It composes the border width, twice the height of
 *    the title font (if one is given) and some padding between the
 *    title.
 *
 * 4) The BOTTOM margin is area from the bottom window border to the
 *    X axis (not including ticks). It composes the border width, the height
 *    an optional X axis label and its padding, the height of the font
 *    of the tick labels.
 *
 * The plotting area is between the margins which includes the X and Y axes
 * including the ticks but not the tick numeric labels. The length of
 * the ticks and its padding is 5% of the entire plotting area.  Hence the
 * entire plotting area is scaled as 105% of the width and height of the
 * area.
 *
 * The axis labels, ticks labels, title, and legend may or may not be
 * displayed which must be taken into account.
 *
 *
 * -----------------------------------------------------------------
 */
void
Blt_LayoutMargins(graphPtr)
    Graph *graphPtr;
{
    int width, height;
    int titleY;
    int left, right, top, bottom;

    ComputeMargins(graphPtr);
    left = graphPtr->leftMargin.width + graphPtr->inset + graphPtr->plotBW;
    right = graphPtr->rightMargin.width + graphPtr->inset + graphPtr->plotBW;
    top = graphPtr->topMargin.height + graphPtr->inset + graphPtr->plotBW;
    bottom = graphPtr->bottomMargin.height + graphPtr->inset + graphPtr->plotBW;

    /* Based upon the margins, calculate the space left for the graph. */
    width = graphPtr->width - (left + right);
    height = graphPtr->height - (top + bottom);
    if (width < 1) {
	width = 1;
    }
    if (height < 1) {
	height = 1;
    }
    graphPtr->left = left;
    graphPtr->right = left + width;
    graphPtr->bottom = top + height;
    graphPtr->top = top;

    graphPtr->vOffset = top + graphPtr->padTop;
    graphPtr->vRange = height - PADDING(graphPtr->padY);
    graphPtr->hOffset = left + graphPtr->padLeft;
    graphPtr->hRange = width - PADDING(graphPtr->padX);
    if (graphPtr->vRange < 1) {
	graphPtr->vRange = 1;
    }
    if (graphPtr->hRange < 1) {
	graphPtr->hRange = 1;
    }

    /*
     * Calculate the placement of the graph title so it is centered within the
     * space provided for it in the top margin
     */
    titleY = graphPtr->titleStyle.height;
    graphPtr->titleY = (titleY / 2) + graphPtr->inset;
    graphPtr->titleX = (graphPtr->right + graphPtr->left) / 2;

}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureAxis --
 *
 *	Configures axis attributes (font, line width, label, etc).
 *
 * Results:
 *	The return value is a standard Tcl result.
 *
 * Side Effects:
 *	Axis layout is deferred until the height and width of the
 *	window are known.
 *
 * ----------------------------------------------------------------------
 */

static int
ConfigureAxis(graphPtr, axisPtr)
    Graph *graphPtr;
    Axis *axisPtr;
{
    char errMsg[200];

    /* Check the requested axis limits. Can't allow -min to be greater
     * than -max, or have undefined log scale limits.  */
    if (((axisPtr->flags & AXIS_CONFIG_BOTH) == AXIS_CONFIG_BOTH) &&
	(axisPtr->min >= axisPtr->max)) {
	sprintf(errMsg, "impossible limits (min %g >= max %g) for axis \"%s\"",
	    axisPtr->min, axisPtr->max, axisPtr->name);
	Tcl_AppendResult(graphPtr->interp, errMsg, (char *)NULL);
	/* Bad values, turn on axis auto-scaling */
	axisPtr->flags &= ~AXIS_CONFIG_BOTH;
	return TCL_ERROR;
    }
    if ((axisPtr->logScale) && (axisPtr->flags & AXIS_CONFIG_MIN) &&
	(axisPtr->min <= 0.0)) {
	sprintf(errMsg, "bad logscale limits (min=%g,max=%g) for axis \"%s\"",
	    axisPtr->min, axisPtr->max, axisPtr->name);
	Tcl_AppendResult(graphPtr->interp, errMsg, (char *)NULL);
	/* Bad minimum value, turn on auto-scaling */
	axisPtr->flags &= ~AXIS_CONFIG_MIN;
	return TCL_ERROR;
    }
    axisPtr->tickStyle.theta = FMOD(axisPtr->tickStyle.theta, 360.0);
    if (axisPtr->tickStyle.theta < 0.0) {
	axisPtr->tickStyle.theta += 360.0;
    }
    ResetTextStyles(graphPtr, axisPtr);

    axisPtr->titleWidth = axisPtr->titleHeight = 0;
    if (axisPtr->titleText != NULL) {
	int w, h;

	Blt_GetTextExtents(&(axisPtr->titleStyle), axisPtr->titleText, &w, &h);
	axisPtr->titleWidth = (short int)w;
	axisPtr->titleHeight = (short int)h;
    }

    /* 
     * Don't bother to check what configuration options have changed.
     * Almost every option changes the size of the plotting area
     * (except for -color and -titlecolor), requiring the graph and
     * its contents to be completely redrawn.
     *
     * Recompute the scale and offset of the axis in case -min, -max
     * options have changed.  
     */
    graphPtr->flags |= REDRAW_WORLD;
    if (!Blt_ConfigModified(configSpecs, "-*color", "-background", "-bg",
		    (char *)NULL)) {
	graphPtr->flags |= (MAP_WORLD | RESET_AXES);
	axisPtr->flags |= AXIS_CONFIG_DIRTY;
    }
    Blt_EventuallyRedrawGraph(graphPtr);

    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * CreateAxis --
 *
 *	Create and initialize a structure containing information to
 * 	display a graph axis.
 *
 * Results:
 *	The return value is a standard Tcl result.
 *
 * ----------------------------------------------------------------------
 */
static Axis *
CreateAxis(graphPtr, name, margin)
    Graph *graphPtr;
    char *name;			/* Identifier for axis. */
    int margin;
{
    Axis *axisPtr;
    Blt_HashEntry *hPtr;
    int isNew;

    if (name[0] == '-') {
	Tcl_AppendResult(graphPtr->interp, "name of axis \"", name, 
			 "\" can't start with a '-'", (char *)NULL);
	return NULL;
    }
    hPtr = Blt_CreateHashEntry(&(graphPtr->axes.table), name, &isNew);
    if (!isNew) {
	axisPtr = (Axis *)Blt_GetHashValue(hPtr);
	if (!axisPtr->deletePending) {
	    Tcl_AppendResult(graphPtr->interp, "axis \"", name,
		"\" already exists in \"", Tk_PathName(graphPtr->tkwin), "\"",
		(char *)NULL);
	    return NULL;
	}
	axisPtr->deletePending = FALSE;
    } else {
	axisPtr = Blt_Calloc(1, sizeof(Axis));
	assert(axisPtr);

	axisPtr->name = Blt_Strdup(name);
	axisPtr->hashPtr = hPtr;
	axisPtr->classUid = NULL;
	axisPtr->looseMin = axisPtr->looseMax = TICK_RANGE_TIGHT;
	axisPtr->reqNumMinorTicks = 2;
	axisPtr->scrollUnits = 10;
	axisPtr->showTicks = TRUE;

	if ((graphPtr->classUid == bltBarElementUid) && 
	    ((margin == MARGIN_TOP) || (margin == MARGIN_BOTTOM))) {
	    axisPtr->reqStep = 1.0;
	    axisPtr->reqNumMinorTicks = 0;
	} 
	if ((margin == MARGIN_RIGHT) || (margin == MARGIN_TOP)) {
	    axisPtr->hidden = TRUE;
	}
	Blt_InitTextStyle(&(axisPtr->titleStyle));
	Blt_InitTextStyle(&(axisPtr->limitsStyle));
	Blt_InitTextStyle(&(axisPtr->tickStyle));
	axisPtr->tickLabels = Blt_ChainCreate();
	axisPtr->lineWidth = 1;
	axisPtr->tickStyle.padX.side1 = axisPtr->tickStyle.padX.side2 = 2;
	Blt_SetHashValue(hPtr, axisPtr);
    }
    return axisPtr;
}

static int
NameToAxis(graphPtr, name, axisPtrPtr)
    Graph *graphPtr;		/* Graph widget record. */
    char *name;			/* Name of the axis to be searched for. */
    Axis **axisPtrPtr;		/* (out) Pointer to found axis structure. */
{
    Blt_HashEntry *hPtr;

    hPtr = Blt_FindHashEntry(&(graphPtr->axes.table), name);
    if (hPtr != NULL) {
	Axis *axisPtr;

	axisPtr = (Axis *)Blt_GetHashValue(hPtr);
	if (!axisPtr->deletePending) {
	    *axisPtrPtr = axisPtr;
	    return TCL_OK;
	}
    }
    Tcl_AppendResult(graphPtr->interp, "can't find axis \"", name,
	    "\" in \"", Tk_PathName(graphPtr->tkwin), "\"", (char *)NULL);
    *axisPtrPtr = NULL;
    return TCL_ERROR;
}

static int
GetAxis(graphPtr, axisName, classUid, axisPtrPtr)
    Graph *graphPtr;
    char *axisName;
    Tk_Uid classUid;
    Axis **axisPtrPtr;
{
    Axis *axisPtr;

    if (NameToAxis(graphPtr, axisName, &axisPtr) != TCL_OK) {
	return TCL_ERROR;
    }
    if (classUid != NULL) {
	if ((axisPtr->refCount == 0) || (axisPtr->classUid == NULL)) {
	    /* Set the axis type on the first use of it. */
	    axisPtr->classUid = classUid;
	} else if (axisPtr->classUid != classUid) {
	    Tcl_AppendResult(graphPtr->interp, "axis \"", axisName,
		"\" is already in use on an opposite ", axisPtr->classUid,
	        "-axis", (char *)NULL);
	    return TCL_ERROR;
	}
	axisPtr->refCount++;
    }
    *axisPtrPtr = axisPtr;
    return TCL_OK;
}

static void
FreeAxis(graphPtr, axisPtr)
    Graph *graphPtr;
    Axis *axisPtr;
{
    axisPtr->refCount--;
    if ((axisPtr->deletePending) && (axisPtr->refCount == 0)) {
	DestroyAxis(graphPtr, axisPtr);
    }
}


void
Blt_DestroyAxes(graphPtr)
    Graph *graphPtr;
{
    Blt_HashEntry *hPtr;
    Blt_HashSearch cursor;
    Axis *axisPtr;
    int i;

    for (hPtr = Blt_FirstHashEntry(&(graphPtr->axes.table), &cursor);
	hPtr != NULL; hPtr = Blt_NextHashEntry(&cursor)) {
	axisPtr = (Axis *)Blt_GetHashValue(hPtr);
	axisPtr->hashPtr = NULL;
	DestroyAxis(graphPtr, axisPtr);
    }
    Blt_DeleteHashTable(&(graphPtr->axes.table));
    for (i = 0; i < 4; i++) {
	Blt_ChainDestroy(graphPtr->axisChain[i]);
    }
    Blt_DeleteHashTable(&(graphPtr->axes.tagTable));
    Blt_ChainDestroy(graphPtr->axes.chainPtr);
}

int
Blt_DefaultAxes(graphPtr)
    Graph *graphPtr;
{
    register int i;
    Axis *axisPtr;
    Blt_Chain *chainPtr;
    static char *axisNames[4] = { "x", "y", "x2", "y2" } ;
    int flags;

    flags = Blt_GraphType(graphPtr);
    for (i = 0; i < 4; i++) {
	chainPtr = Blt_ChainCreate();
	graphPtr->axisChain[i] = chainPtr;

	/* Create a default axis for each chain. */
	axisPtr = CreateAxis(graphPtr, axisNames[i], i);
	if (axisPtr == NULL) {
	    return TCL_ERROR;
	}
	axisPtr->refCount = 1;
	axisPtr->classUid = (i & 1) ? bltYAxisUid : bltXAxisUid;

	/*
	 * Blt_ConfigureWidgetComponent creates a temporary child window 
	 * by the name of the axis.  It's used so that the Tk routines
	 * that access the X resource database can describe a single 
	 * component and not the entire graph.
	 */
	if (Blt_ConfigureWidgetComponent(graphPtr->interp, graphPtr->tkwin,
		axisPtr->name, "Axis", configSpecs, 0, (char **)NULL,
		(char *)axisPtr, flags) != TCL_OK) {
	    return TCL_ERROR;
	}
	if (ConfigureAxis(graphPtr, axisPtr) != TCL_OK) {
	    return TCL_ERROR;
	}
	axisPtr->linkPtr = Blt_ChainAppend(chainPtr, axisPtr);
	axisPtr->chainPtr = chainPtr;
    }
    return TCL_OK;
}


/*----------------------------------------------------------------------
 *
 * BindOp --
 *
 *    .g axis bind axisName sequence command
 *
 *----------------------------------------------------------------------
 */
static int
BindOp(graphPtr, axisPtr, argc, argv)
    Graph *graphPtr;
    Axis *axisPtr;
    int argc;
    char **argv;
{
    Tcl_Interp *interp = graphPtr->interp;

    return Blt_ConfigureBindings(interp, graphPtr->bindTable,
          Blt_MakeAxisTag(graphPtr, axisPtr->name), argc, argv);
}
          
/*
 * ----------------------------------------------------------------------
 *
 * CgetOp --
 *
 *	Queries axis attributes (font, line width, label, etc).
 *
 * Results:
 *	Return value is a standard Tcl result.  If querying configuration
 *	values, interp->result will contain the results.
 *
 * ----------------------------------------------------------------------
 */
/* ARGSUSED */
static int
CgetOp(graphPtr, axisPtr, argc, argv)
    Graph *graphPtr;
    Axis *axisPtr;
    int argc;			/* Not used. */
    char *argv[];
{
    return Tk_ConfigureValue(graphPtr->interp, graphPtr->tkwin, configSpecs,
	(char *)axisPtr, argv[0], Blt_GraphType(graphPtr));
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureOp --
 *
 *	Queries or resets axis attributes (font, line width, label, etc).
 *
 * Results:
 *	Return value is a standard Tcl result.  If querying configuration
 *	values, interp->result will contain the results.
 *
 * Side Effects:
 *	Axis resources are possibly allocated (GC, font). Axis layout is
 *	deferred until the height and width of the window are known.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureOp(graphPtr, axisPtr, argc, argv)
    Graph *graphPtr;
    Axis *axisPtr;
    int argc;
    char *argv[];
{
    int flags;

    flags = TK_CONFIG_ARGV_ONLY | Blt_GraphType(graphPtr);
    if (argc == 0) {
	return Tk_ConfigureInfo(graphPtr->interp, graphPtr->tkwin, configSpecs,
	    (char *)axisPtr, (char *)NULL, flags);
    } else if (argc == 1) {
	return Tk_ConfigureInfo(graphPtr->interp, graphPtr->tkwin, configSpecs,
	    (char *)axisPtr, argv[0], flags);
    }
    if (Tk_ConfigureWidget(graphPtr->interp, graphPtr->tkwin, configSpecs,
	    argc, argv, (char *)axisPtr, flags) != TCL_OK) {
	return TCL_ERROR;
    }
    if (ConfigureAxis(graphPtr, axisPtr) != TCL_OK) {
	return TCL_ERROR;
    }
    if (axisPtr->refCount > 0) {
	if (!Blt_ConfigModified(configSpecs, "-*color", "-background", "-bg",
				(char *)NULL)) {
	    graphPtr->flags |= REDRAW_BACKING_STORE;
	}
	graphPtr->flags |= DRAW_MARGINS;
	Blt_EventuallyRedrawGraph(graphPtr);
    }
    return TCL_OK;
}


/*
 * ----------------------------------------------------------------------
 *
 * GetOp --
 *
 *    Returns the name of the picked axis (using the axis
 *    bind operation).  Right now, the only name accepted is
 *    "current".
 *
 * Results:
 *    A standard Tcl result.  The interpreter result will contain
 *    the name of the axis.
 *
 * ----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
GetOp(graphPtr, argc, argv)
    Graph *graphPtr;
    int argc;                 /* Not used. */
    char *argv[];
{
    Tcl_Interp *interp = graphPtr->interp;
    register Axis *axisPtr;

    axisPtr = (Axis *)Blt_GetCurrentItem(graphPtr->bindTable);
    /* Report only on axes. */
    if ((axisPtr != NULL) && 
	((axisPtr->classUid == bltXAxisUid) ||
	 (axisPtr->classUid == bltYAxisUid) || 
	 (axisPtr->classUid == NULL))) {
	char c;
	
	c = argv[3][0];
	if ((c == 'c') && (strcmp(argv[3], "current") == 0)) {
	    Tcl_SetResult(interp, axisPtr->name, TCL_VOLATILE);
	} else if ((c == 'd') && (strcmp(argv[3], "detail") == 0)) {
	    Tcl_SetResult(interp, axisPtr->detail, TCL_VOLATILE);
	}
    }
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * LimitsOp --
 *
 *	This procedure returns a string representing the axis limits
 *	of the graph.  The format of the string is { left top right bottom}.
 *
 * Results:
 *	Always returns TCL_OK.  The interp->result field is
 *	a list of the graph axis limits.
 *
 *--------------------------------------------------------------
 */
/*ARGSUSED*/
static int
LimitsOp(graphPtr, axisPtr, argc, argv)
    Graph *graphPtr;
    Axis *axisPtr;
    int argc;			/* Not used. */
    char **argv;		/* Not used. */

{
    Tcl_Interp *interp = graphPtr->interp;
    double min, max;

    if (graphPtr->flags & RESET_AXES) {
	Blt_ResetAxes(graphPtr);
    }
    if (axisPtr->logScale) {
	min = EXP10(axisPtr->tickRange.min);
	max = EXP10(axisPtr->tickRange.max);
    } else {
	min = axisPtr->tickRange.min;
	max = axisPtr->tickRange.max;
    }
    Tcl_AppendElement(interp, Blt_Dtoa(interp, min));
    Tcl_AppendElement(interp, Blt_Dtoa(interp, max));
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * InvTransformOp --
 *
 *	Maps the given window coordinate into an axis-value.
 *
 * Results:
 *	Returns a standard Tcl result.  interp->result contains
 *	the axis value. If an error occurred, TCL_ERROR is returned
 *	and interp->result will contain an error message.
 *
 * ----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
InvTransformOp(graphPtr, axisPtr, argc, argv)
    Graph *graphPtr;
    Axis *axisPtr;
    int argc;			/* Not used. */
    char **argv;
{
    int x;			/* Integer window coordinate*/
    double y;			/* Real graph coordinate */

    if (graphPtr->flags & RESET_AXES) {
	Blt_ResetAxes(graphPtr);
    }
    if (Tcl_GetInt(graphPtr->interp, argv[0], &x) != TCL_OK) {
	return TCL_ERROR;
    }
    /*
     * Is the axis vertical or horizontal?
     *
     * Check the site where the axis was positioned.  If the axis is
     * virtual, all we have to go on is how it was mapped to an
     * element (using either -mapx or -mapy options).  
     */
    if (AxisIsHorizontal(graphPtr, axisPtr)) {
	y = InvHMap(graphPtr, axisPtr, (double)x);
    } else {
	y = InvVMap(graphPtr, axisPtr, (double)x);
    }
    Tcl_AppendElement(graphPtr->interp, Blt_Dtoa(graphPtr->interp, y));
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * TransformOp --
 *
 *	Maps the given axis-value to a window coordinate.
 *
 * Results:
 *	Returns a standard Tcl result.  interp->result contains
 *	the window coordinate. If an error occurred, TCL_ERROR
 *	is returned and interp->result will contain an error
 *	message.
 *
 * ----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
TransformOp(graphPtr, axisPtr, argc, argv)
    Graph *graphPtr;
    Axis *axisPtr;		/* Axis */
    int argc;			/* Not used. */
    char **argv;
{
    double x;

    if (graphPtr->flags & RESET_AXES) {
	Blt_ResetAxes(graphPtr);
    }
    if (Tcl_ExprDouble(graphPtr->interp, argv[0], &x) != TCL_OK) {
	return TCL_ERROR;
    }
    if (AxisIsHorizontal(graphPtr, axisPtr)) {
	x = HMap(graphPtr, axisPtr, x);
    } else {
	x = VMap(graphPtr, axisPtr, x);
    }
    Tcl_SetResult(graphPtr->interp, Blt_Itoa((int)x), TCL_VOLATILE);
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * UseOp --
 *
 *	Changes the virtual axis used by the logical axis.
 *
 * Results:
 *	A standard Tcl result.  If the named axis doesn't exist
 *	an error message is put in interp->result.
 *
 * .g xaxis use "abc def gah"
 * .g xaxis use [lappend abc [.g axis use]]
 *
 *--------------------------------------------------------------
 */
/*ARGSUSED*/
static int
UseOp(graphPtr, axisPtr, argc, argv)
    Graph *graphPtr;
    Axis *axisPtr;		/* Not used. */
    int argc;
    char **argv;
{
    Blt_Chain *chainPtr;
    int nElem;
    char **elemArr;
    Blt_ChainLink *linkPtr;
    int i;
    Tk_Uid classUid;
    int margin;

    margin = (int)argv[-1];
    chainPtr = graphPtr->margins[margin].chainPtr;
    if (argc == 0) {
	for (linkPtr = Blt_ChainFirstLink(chainPtr); linkPtr!= NULL;
	     linkPtr = Blt_ChainNextLink(linkPtr)) {
	    axisPtr = Blt_ChainGetValue(linkPtr);
	    Tcl_AppendElement(graphPtr->interp, axisPtr->name);
	}
	return TCL_OK;
    }
    if ((margin == MARGIN_BOTTOM) || (margin == MARGIN_TOP)) {
	classUid = (graphPtr->inverted) ? bltYAxisUid : bltXAxisUid;
    } else {
	classUid = (graphPtr->inverted) ? bltXAxisUid : bltYAxisUid;
    }
    if (Tcl_SplitList(graphPtr->interp, argv[0], &nElem, &elemArr) != TCL_OK) {
	return TCL_ERROR;
    }
    for (linkPtr = Blt_ChainFirstLink(chainPtr); linkPtr!= NULL;
	 linkPtr = Blt_ChainNextLink(linkPtr)) {
	axisPtr = Blt_ChainGetValue(linkPtr);
	axisPtr->linkPtr = NULL;
	/* Clear the type of axes not currently mapped to elements.*/
	if (!(axisPtr->flags & AXIS_MAPS_ELEM)) {
	    axisPtr->classUid = NULL; 
	}
    }
    Blt_ChainReset(chainPtr);
    for (i = 0; i < nElem; i++) {
	if (NameToAxis(graphPtr, elemArr[i], &axisPtr) != TCL_OK) {
	    Blt_Free(elemArr);
	    return TCL_ERROR;
	}
	if (axisPtr->classUid == NULL) {
	    axisPtr->classUid = classUid; 
	} else if (axisPtr->classUid != classUid) {
	    Tcl_AppendResult(graphPtr->interp, "wrong type axis \"", 
		     axisPtr->name, "\": can't use ", classUid, " type axis.", 
		     (char *)NULL);			     
	    Blt_Free(elemArr);
	    return TCL_ERROR;
	}
	if (axisPtr->linkPtr != NULL) {
	    /* Move the axis from the old margin's "use" list to the new. */
	    Blt_ChainUnlinkLink(axisPtr->chainPtr, axisPtr->linkPtr);
	    Blt_ChainAppendLink(chainPtr, axisPtr->linkPtr);
	} else {
	    axisPtr->linkPtr = Blt_ChainAppend(chainPtr, axisPtr);
	}
	axisPtr->chainPtr = chainPtr;
    }
    graphPtr->flags |= (GET_AXIS_GEOMETRY | LAYOUT_NEEDED | RESET_AXES);
    /* When any axis changes, we need to layout the entire graph.  */
    graphPtr->flags |= (MAP_WORLD | REDRAW_WORLD);
    Blt_EventuallyRedrawGraph(graphPtr);
    
    Blt_Free(elemArr);
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * CreateVirtualOp --
 *
 *	Creates a new axis.
 *
 * Results:
 *	Returns a standard Tcl result.
 *
 * ----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
CreateVirtualOp(graphPtr, argc, argv)
    Graph *graphPtr;
    int argc;
    char **argv;
{
    Axis *axisPtr;
    int flags;

    axisPtr = CreateAxis(graphPtr, argv[3], MARGIN_NONE);
    if (axisPtr == NULL) {
	return TCL_ERROR;
    }
    flags = Blt_GraphType(graphPtr);
    if (Blt_ConfigureWidgetComponent(graphPtr->interp, graphPtr->tkwin,
	    axisPtr->name, "Axis", configSpecs, argc - 4, argv + 4,
	    (char *)axisPtr, flags) != TCL_OK) {
	goto error;
    }
    if (ConfigureAxis(graphPtr, axisPtr) != TCL_OK) {
	goto error;
    }
    Tcl_SetResult(graphPtr->interp, axisPtr->name, TCL_VOLATILE);
    return TCL_OK;
  error:
    DestroyAxis(graphPtr, axisPtr);
    return TCL_ERROR;
}

/*----------------------------------------------------------------------
 *
 * BindVirtualOp --
 *
 *    .g axis bind axisName sequence command
 *
 *----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
BindVirtualOp(graphPtr, argc, argv)
    Graph *graphPtr;
    int argc;
    char **argv;
{
    Tcl_Interp *interp = graphPtr->interp;

    if (argc == 3) {
	Blt_HashEntry *hPtr;
	Blt_HashSearch cursor;
	char *tagName;

	for (hPtr = Blt_FirstHashEntry(&(graphPtr->axes.tagTable), &cursor);
	     hPtr != NULL; hPtr = Blt_NextHashEntry(&cursor)) {
	    tagName = Blt_GetHashKey(&(graphPtr->axes.tagTable), hPtr);
	    Tcl_AppendElement(interp, tagName);
	}
	return TCL_OK;
    }
    return Blt_ConfigureBindings(interp, graphPtr->bindTable, 
	 Blt_MakeAxisTag(graphPtr, argv[3]), argc - 4, argv + 4);
}


/*
 * ----------------------------------------------------------------------
 *
 * CgetVirtualOp --
 *
 *	Queries axis attributes (font, line width, label, etc).
 *
 * Results:
 *	Return value is a standard Tcl result.  If querying configuration
 *	values, interp->result will contain the results.
 *
 * ----------------------------------------------------------------------
 */
/* ARGSUSED */
static int
CgetVirtualOp(graphPtr, argc, argv)
    Graph *graphPtr;
    int argc;
    char *argv[];
{
    Axis *axisPtr;

    if (NameToAxis(graphPtr, argv[3], &axisPtr) != TCL_OK) {
	return TCL_ERROR;
    }
    return CgetOp(graphPtr, axisPtr, argc - 4, argv + 4);
}

/*
 * ----------------------------------------------------------------------
 *
 * ConfigureVirtualOp --
 *
 *	Queries or resets axis attributes (font, line width, label, etc).
 *
 * Results:
 *	Return value is a standard Tcl result.  If querying configuration
 *	values, interp->result will contain the results.
 *
 * Side Effects:
 *	Axis resources are possibly allocated (GC, font). Axis layout is
 *	deferred until the height and width of the window are known.
 *
 * ----------------------------------------------------------------------
 */
static int
ConfigureVirtualOp(graphPtr, argc, argv)
    Graph *graphPtr;
    int argc;
    char *argv[];
{
    Axis *axisPtr;
    int nNames, nOpts;
    char **options;
    register int i;

    /* Figure out where the option value pairs begin */
    argc -= 3;
    argv += 3;
    for (i = 0; i < argc; i++) {
	if (argv[i][0] == '-') {
	    break;
	}
	if (NameToAxis(graphPtr, argv[i], &axisPtr) != TCL_OK) {
	    return TCL_ERROR;
	}
    }
    nNames = i;			/* Number of pen names specified */
    nOpts = argc - i;		/* Number of options specified */
    options = argv + i;		/* Start of options in argv  */

    for (i = 0; i < nNames; i++) {
	if (NameToAxis(graphPtr, argv[i], &axisPtr) != TCL_OK) {
	    return TCL_ERROR;
	}
	if (ConfigureOp(graphPtr, axisPtr, nOpts, options) != TCL_OK) {
	    break;
	}
    }
    if (i < nNames) {
	return TCL_ERROR;
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * DeleteVirtualOp --
 *
 *	Deletes one or more axes.  The actual removal may be deferred
 *	until the axis is no longer used by any element. The axis
 *	can't be referenced by its name any longer and it may be
 *	recreated.
 *
 * Results:
 *	Returns a standard Tcl result.
 *
 * ----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
DeleteVirtualOp(graphPtr, argc, argv)
    Graph *graphPtr;
    int argc;
    char **argv;
{
    register int i;
    Axis *axisPtr;

    for (i = 3; i < argc; i++) {
	if (NameToAxis(graphPtr, argv[i], &axisPtr) != TCL_OK) {
	    return TCL_ERROR;
	}
	axisPtr->deletePending = TRUE;
	if (axisPtr->refCount == 0) {
	    DestroyAxis(graphPtr, axisPtr);
	}
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * InvTransformVirtualOp --
 *
 *	Maps the given window coordinate into an axis-value.
 *
 * Results:
 *	Returns a standard Tcl result.  interp->result contains
 *	the axis value. If an error occurred, TCL_ERROR is returned
 *	and interp->result will contain an error message.
 *
 * ----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
InvTransformVirtualOp(graphPtr, argc, argv)
    Graph *graphPtr;
    int argc;			/* Not used. */
    char **argv;
{
    Axis *axisPtr;

    if (NameToAxis(graphPtr, argv[3], &axisPtr) != TCL_OK) {
	return TCL_ERROR;
    }
    return InvTransformOp(graphPtr, axisPtr, argc - 4, argv + 4);
}

/*
 *--------------------------------------------------------------
 *
 * LimitsVirtualOp --
 *
 *	This procedure returns a string representing the axis limits
 *	of the graph.  The format of the string is { left top right bottom}.
 *
 * Results:
 *	Always returns TCL_OK.  The interp->result field is
 *	a list of the graph axis limits.
 *
 *--------------------------------------------------------------
 */
/*ARGSUSED*/
static int
LimitsVirtualOp(graphPtr, argc, argv)
    Graph *graphPtr;
    int argc;			/* Not used. */
    char **argv;		/* Not used. */

{
    Axis *axisPtr;

    if (NameToAxis(graphPtr, argv[3], &axisPtr) != TCL_OK) {
	return TCL_ERROR;
    }
    return LimitsOp(graphPtr, axisPtr, argc - 4, argv + 4);
}

/*
 * ----------------------------------------------------------------------
 *
 * NamesVirtualOp --
 *
 *	Return a list of the names of all the axes.
 *
 * Results:
 *	Returns a standard Tcl result.
 *
 * ----------------------------------------------------------------------
 */

/*ARGSUSED*/
static int
NamesVirtualOp(graphPtr, argc, argv)
    Graph *graphPtr;
    int argc;			/* Not used. */
    char **argv;		/* Not used. */
{
    Blt_HashEntry *hPtr;
    Blt_HashSearch cursor;
    Axis *axisPtr;
    register int i;

    for (hPtr = Blt_FirstHashEntry(&(graphPtr->axes.table), &cursor);
	hPtr != NULL; hPtr = Blt_NextHashEntry(&cursor)) {
	axisPtr = (Axis *)Blt_GetHashValue(hPtr);
	if (axisPtr->deletePending) {
	    continue;
	}
	if (argc == 3) {
	    Tcl_AppendElement(graphPtr->interp, axisPtr->name);
	    continue;
	}
	for (i = 3; i < argc; i++) {
	    if (Tcl_StringMatch(axisPtr->name, argv[i])) {
		Tcl_AppendElement(graphPtr->interp, axisPtr->name);
		break;
	    }
	}
    }
    return TCL_OK;
}

/*
 * ----------------------------------------------------------------------
 *
 * TransformVirtualOp --
 *
 *	Maps the given axis-value to a window coordinate.
 *
 * Results:
 *	Returns a standard Tcl result.  interp->result contains
 *	the window coordinate. If an error occurred, TCL_ERROR
 *	is returned and interp->result will contain an error
 *	message.
 *
 * ----------------------------------------------------------------------
 */
/*ARGSUSED*/
static int
TransformVirtualOp(graphPtr, argc, argv)
    Graph *graphPtr;
    int argc;			/* Not used. */
    char **argv;
{
    Axis *axisPtr;

    if (NameToAxis(graphPtr, argv[3], &axisPtr) != TCL_OK) {
	return TCL_ERROR;
    }
    return TransformOp(graphPtr, axisPtr, argc - 4, argv + 4);
}

static int
ViewOp(graphPtr, argc, argv)
    Graph *graphPtr;
    int argc;
    char **argv;
{
    Tcl_Interp *interp = graphPtr->interp;
    double width, worldWidth;
    double axisOffset, scrollUnits;
    double fract;
    Axis *axisPtr;
    double min, max, worldMin, worldMax;

    if (NameToAxis(graphPtr, argv[3], &axisPtr) != TCL_OK) {
	return TCL_ERROR;
    }
    worldMin = axisPtr->dataRange.min;
    worldMax = axisPtr->dataRange.max;
    min = axisPtr->min;
    max = axisPtr->max;
    if (axisPtr->logScale) {
	worldMin = log10(worldMin);
	worldMax = log10(worldMax);
	min = log10(min);
	max = log10(max);
    }
    worldWidth = worldMax - worldMin;
    width = max - min;

    /* Unlike horizontal axes, vertical axis values run opposite of
     * the scrollbar first/last values.  So instead of pushing the
     * axis minimum around, we move the maximum instead. */

    if (AxisIsHorizontal(graphPtr, axisPtr) != axisPtr->descending) {
	axisOffset = min - worldMin;
	scrollUnits = (double)axisPtr->scrollUnits / (double)graphPtr->hRange;
    } else {
	axisOffset = worldMax - max;
	scrollUnits = (double)axisPtr->scrollUnits / (double)graphPtr->vRange;
    }
    if (argc == 4) {
	/* Note: Bound the fractions between 0.0 and 1.0 to support
	 * "canvas"-style scrolling. */
	fract = axisOffset / worldWidth;
	Tcl_AppendElement(interp, Blt_Dtoa(interp, CLAMP(fract, 0.0, 1.0)));
	fract = (axisOffset + width) / worldWidth;
	Tcl_AppendElement(interp, Blt_Dtoa(interp, CLAMP(fract, 0.0, 1.0)));
	return TCL_OK;
    }
    fract = axisOffset / worldWidth;
    if (GetAxisScrollInfo(interp, argc - 4, argv + 4, &fract, 
		width / worldWidth, scrollUnits) != TCL_OK) {
	return TCL_ERROR;
    }
    if (AxisIsHorizontal(graphPtr, axisPtr) != axisPtr->descending) {
	axisPtr->min = (fract * worldWidth) + worldMin;
	axisPtr->max = axisPtr->min + width;
    } else {
	axisPtr->max = worldMax - (fract * worldWidth);
	axisPtr->min = axisPtr->max - width;
    }
    if (axisPtr->logScale) {
	axisPtr->min = EXP10(axisPtr->min);
	axisPtr->max = EXP10(axisPtr->max);
    }
    graphPtr->flags |= (GET_AXIS_GEOMETRY | LAYOUT_NEEDED | RESET_AXES);
    Blt_EventuallyRedrawGraph(graphPtr);
    return TCL_OK;
}

int
Blt_VirtualAxisOp(graphPtr, interp, argc, argv)
    Graph *graphPtr;
    Tcl_Interp *interp;
    int argc;
    char **argv;
{
    Blt_Op proc;
    int result;
    static Blt_OpSpec axisOps[] =
    {
	{"bind", 1, (Blt_Op)BindVirtualOp, 3, 6, 
	     "axisName sequence command",},
	{"cget", 2, (Blt_Op)CgetVirtualOp, 5, 5, "axisName option",},
	{"configure", 2, (Blt_Op)ConfigureVirtualOp, 4, 0,
	    "axisName ?axisName?... ?option value?...",},
	{"create", 2, (Blt_Op)CreateVirtualOp, 4, 0,
	    "axisName ?option value?...",},
	{"delete", 1, (Blt_Op)DeleteVirtualOp, 3, 0, "?axisName?...",},
	{"get", 1, (Blt_Op)GetOp, 4, 4, "name",},
	{"invtransform", 1, (Blt_Op)InvTransformVirtualOp, 5, 5,
	    "axisName value",},
	{"limits", 1, (Blt_Op)LimitsVirtualOp, 4, 4, "axisName",},
	{"names", 1, (Blt_Op)NamesVirtualOp, 3, 0, "?pattern?...",},
	{"transform", 1, (Blt_Op)TransformVirtualOp, 5, 5, "axisName value",},
	{"view", 1, (Blt_Op)ViewOp, 4, 7,
	    "axisName ?moveto fract? ?scroll number what?",},
    };
    static int nAxisOps = sizeof(axisOps) / sizeof(Blt_OpSpec);

    proc = Blt_GetOp(interp, nAxisOps, axisOps, BLT_OP_ARG2, argc, argv, 0);
    if (proc == NULL) {
	return TCL_ERROR;
    }
    result = (*proc) (graphPtr, argc, argv);
    return result;
}

int
Blt_AxisOp(graphPtr, margin, argc, argv)
    Graph *graphPtr;
    int margin;
    int argc;
    char **argv;
{
    int result;
    Blt_Op proc;
    Axis *axisPtr;
    static Blt_OpSpec axisOps[] =
    {
	{"bind", 1, (Blt_Op)BindOp, 2, 5, "sequence command",},
	{"cget", 2, (Blt_Op)CgetOp, 4, 4, "option",},
	{"configure", 2, (Blt_Op)ConfigureOp, 3, 0, "?option value?...",},
	{"invtransform", 1, (Blt_Op)InvTransformOp, 4, 4, "value",},
	{"limits", 1, (Blt_Op)LimitsOp, 3, 3, "",},
	{"transform", 1, (Blt_Op)TransformOp, 4, 4, "value",},
	{"use", 1, (Blt_Op)UseOp, 3, 4, "?axisName?",},
    };
    static int nAxisOps = sizeof(axisOps) / sizeof(Blt_OpSpec);

    proc = Blt_GetOp(graphPtr->interp, nAxisOps, axisOps, BLT_OP_ARG2, 
	argc, argv, 0);
    if (proc == NULL) {
	return TCL_ERROR;
    }
    argv[2] = (char *)margin; /* Hack. Slide a reference to the margin in 
			       * the argument list. Needed only for UseOp.
			       */
    axisPtr = Blt_GetFirstAxis(graphPtr->margins[margin].chainPtr);
    result = (*proc)(graphPtr, axisPtr, argc - 3, argv + 3);
    return result;
}

void
Blt_MapAxes(graphPtr)
    Graph *graphPtr;
{
    Axis *axisPtr;
    Blt_Chain *chainPtr;
    Blt_ChainLink *linkPtr;
    register int margin;
    int offset;
    
    for (margin = 0; margin < 4; margin++) {
	chainPtr = graphPtr->margins[margin].chainPtr;
	offset = 0;
	for (linkPtr = Blt_ChainFirstLink(chainPtr); linkPtr != NULL;
	     linkPtr = Blt_ChainNextLink(linkPtr)) {
	    axisPtr = Blt_ChainGetValue(linkPtr);
	    if (axisPtr->hidden) {
		continue;
	    }
	    MapAxis(graphPtr, axisPtr, offset, margin);
	    if (AxisIsHorizontal(graphPtr, axisPtr)) {
		offset += axisPtr->height;
	    } else {
		offset += axisPtr->width;
	    }
	}
    }
}

void
Blt_DrawAxes(graphPtr, drawable)
    Graph *graphPtr;
    Drawable drawable;
{
    Axis *axisPtr;
    Blt_Chain *chainPtr;
    Blt_ChainLink *linkPtr;
    register int i;

    for (i = 0; i < 4; i++) {
	chainPtr = graphPtr->margins[i].chainPtr;
	for (linkPtr = Blt_ChainFirstLink(chainPtr); linkPtr != NULL;
	     linkPtr = Blt_ChainNextLink(linkPtr)) {
	    axisPtr = Blt_ChainGetValue(linkPtr);
	    if (!axisPtr->hidden) {
		DrawAxis(graphPtr, drawable, axisPtr);
	    }
	}
    }
}

void
Blt_AxesToPostScript(graphPtr, psToken)
    Graph *graphPtr;
    PsToken psToken;
{
    Axis *axisPtr;
    Blt_Chain *chainPtr;
    Blt_ChainLink *linkPtr;
    register int i;

    for (i = 0; i < 4; i++) {
	chainPtr = graphPtr->margins[i].chainPtr;
	for (linkPtr = Blt_ChainFirstLink(chainPtr); linkPtr != NULL;
	     linkPtr = Blt_ChainNextLink(linkPtr)) {
	    axisPtr = Blt_ChainGetValue(linkPtr);
	    if (!axisPtr->hidden) {
		AxisToPostScript(psToken, axisPtr);
	    }
	}
    }
}


/*
 * ----------------------------------------------------------------------
 *
 * Blt_DrawAxisLimits --
 *
 *	Draws the min/max values of the axis in the plotting area. 
 *	The text strings are formatted according to the "sprintf"
 *	format descriptors in the limitsFormats array.
 *
 * Results:
 *	None.
 *
 * Side Effects:
 *	Draws the numeric values of the axis limits into the outer
 *	regions of the plotting area.
 *
 * ----------------------------------------------------------------------
 */
void
Blt_DrawAxisLimits(graphPtr, drawable)
    Graph *graphPtr;
    Drawable drawable;
{
    Axis *axisPtr;
    Blt_HashEntry *hPtr;
    Blt_HashSearch cursor;
    Dim2D textDim;
    int isHoriz;
    char *minPtr, *maxPtr;
    char *minFormat, *maxFormat;
    char minString[200], maxString[200];
    int vMin, hMin, vMax, hMax;

#define SPACING 8
    vMin = vMax = graphPtr->left + graphPtr->padLeft + 2;
    hMin = hMax = graphPtr->bottom - graphPtr->padBottom - 2;	/* Offsets */

    for (hPtr = Blt_FirstHashEntry(&(graphPtr->axes.table), &cursor);
	hPtr != NULL; hPtr = Blt_NextHashEntry(&cursor)) {
	axisPtr = (Axis *)Blt_GetHashValue(hPtr);

	if (axisPtr->nFormats == 0) {
	    continue;
	}
	isHoriz = AxisIsHorizontal(graphPtr, axisPtr);
	minPtr = maxPtr = NULL;
	minFormat = maxFormat = axisPtr->limitsFormats[0];
	if (axisPtr->nFormats > 1) {
	    maxFormat = axisPtr->limitsFormats[1];
	}
	if (minFormat[0] != '\0') {
	    minPtr = minString;
	    sprintf(minString, minFormat, axisPtr->tickRange.min);
	}
	if (maxFormat[0] != '\0') {
	    maxPtr = maxString;
	    sprintf(maxString, maxFormat, axisPtr->tickRange.max);
	}
	if (axisPtr->descending) {
	    char *tmp;

	    tmp = minPtr, minPtr = maxPtr, maxPtr = tmp;
	}
	if (maxPtr != NULL) {
	    if (isHoriz) {
		axisPtr->limitsStyle.theta = 90.0;
		axisPtr->limitsStyle.anchor = TK_ANCHOR_SE;
		Blt_DrawText2(graphPtr->tkwin, drawable, maxPtr,
		    &(axisPtr->limitsStyle), graphPtr->right, hMax, &textDim);
		hMax -= (textDim.height + SPACING);
	    } else {
		axisPtr->limitsStyle.theta = 0.0;
		axisPtr->limitsStyle.anchor = TK_ANCHOR_NW;
		Blt_DrawText2(graphPtr->tkwin, drawable, maxPtr,
		    &(axisPtr->limitsStyle), vMax, graphPtr->top, &textDim);
		vMax += (textDim.width + SPACING);
	    }
	}
	if (minPtr != NULL) {
	    axisPtr->limitsStyle.anchor = TK_ANCHOR_SW;
	    if (isHoriz) {
		axisPtr->limitsStyle.theta = 90.0;
		Blt_DrawText2(graphPtr->tkwin, drawable, minPtr,
		    &(axisPtr->limitsStyle), graphPtr->left, hMin, &textDim);
		hMin -= (textDim.height + SPACING);
	    } else {
		axisPtr->limitsStyle.theta = 0.0;
		Blt_DrawText2(graphPtr->tkwin, drawable, minPtr,
		    &(axisPtr->limitsStyle), vMin, graphPtr->bottom, &textDim);
		vMin += (textDim.width + SPACING);
	    }
	}
    }				/* Loop on axes */
}

void
Blt_AxisLimitsToPostScript(graphPtr, psToken)
    Graph *graphPtr;
    PsToken psToken;
{
    Axis *axisPtr;
    Blt_HashEntry *hPtr;
    Blt_HashSearch cursor;
    double vMin, hMin, vMax, hMax;
    char string[200];
    int textWidth, textHeight;
    char *minFmt, *maxFmt;

#define SPACING 8
    vMin = vMax = graphPtr->left + graphPtr->padLeft + 2;
    hMin = hMax = graphPtr->bottom - graphPtr->padBottom - 2;	/* Offsets */
    for (hPtr = Blt_FirstHashEntry(&(graphPtr->axes.table), &cursor);
	hPtr != NULL; hPtr = Blt_NextHashEntry(&cursor)) {
	axisPtr = (Axis *)Blt_GetHashValue(hPtr);

	if (axisPtr->nFormats == 0) {
	    continue;
	}
	minFmt = maxFmt = axisPtr->limitsFormats[0];
	if (axisPtr->nFormats > 1) {
	    maxFmt = axisPtr->limitsFormats[1];
	}
	if (*maxFmt != '\0') {
	    sprintf(string, maxFmt, axisPtr->tickRange.max);
	    Blt_GetTextExtents(&(axisPtr->tickStyle), string, &textWidth,
		&textHeight);
	    if ((textWidth > 0) && (textHeight > 0)) {
		if (axisPtr->classUid == bltXAxisUid) {
		    axisPtr->limitsStyle.theta = 90.0;
		    axisPtr->limitsStyle.anchor = TK_ANCHOR_SE;
		    Blt_TextToPostScript(psToken, string, 
					 &(axisPtr->limitsStyle), 
					 (double)graphPtr->right, hMax);
		    hMax -= (textWidth + SPACING);
		} else {
		    axisPtr->limitsStyle.theta = 0.0;
		    axisPtr->limitsStyle.anchor = TK_ANCHOR_NW;
		    Blt_TextToPostScript(psToken, string, 
			 &(axisPtr->limitsStyle), vMax, (double)graphPtr->top);
		    vMax += (textWidth + SPACING);
		}
	    }
	}
	if (*minFmt != '\0') {
	    sprintf(string, minFmt, axisPtr->tickRange.min);
	    Blt_GetTextExtents(&(axisPtr->tickStyle), string, &textWidth,
		&textHeight);
	    if ((textWidth > 0) && (textHeight > 0)) {
		axisPtr->limitsStyle.anchor = TK_ANCHOR_SW;
		if (axisPtr->classUid == bltXAxisUid) {
		    axisPtr->limitsStyle.theta = 90.0;
		    Blt_TextToPostScript(psToken, string, 
					 &(axisPtr->limitsStyle), 
					 (double)graphPtr->left, hMin);
		    hMin -= (textWidth + SPACING);
		} else {
		    axisPtr->limitsStyle.theta = 0.0;
		    Blt_TextToPostScript(psToken, string, 
					 &(axisPtr->limitsStyle), 
					 vMin, (double)graphPtr->bottom);
		    vMin += (textWidth + SPACING);
		}
	    }
	}
    }
}

Axis *
Blt_GetFirstAxis(chainPtr)
    Blt_Chain *chainPtr;
{
    Blt_ChainLink *linkPtr;

    linkPtr = Blt_ChainFirstLink(chainPtr);
    if (linkPtr == NULL) {
	return NULL;
    }
    return Blt_ChainGetValue(linkPtr);
}

Axis *
Blt_NearestAxis(graphPtr, x, y)
    Graph *graphPtr;
    int x, y;                 /* Point to be tested */
{
    register Blt_HashEntry *hPtr;
    Blt_HashSearch cursor;
    Axis *axisPtr;
    int w, h;
    Point2D bbox[5];
    
    for (hPtr = Blt_FirstHashEntry(&(graphPtr->axes.table), &cursor);
	 hPtr != NULL; hPtr = Blt_NextHashEntry(&cursor)) {
	axisPtr = (Axis *)Blt_GetHashValue(hPtr);
	if (axisPtr->hidden) {
	    continue;
	}
	if (axisPtr->showTicks) {
	    register Blt_ChainLink *linkPtr;
	    TickLabel *labelPtr;
	    Point2D t;

	    for (linkPtr = Blt_ChainFirstLink(axisPtr->tickLabels); 
		 linkPtr != NULL; linkPtr = Blt_ChainNextLink(linkPtr)) {	
		labelPtr = Blt_ChainGetValue(linkPtr);
		Blt_GetBoundingBox(labelPtr->width, labelPtr->height, 
			axisPtr->tickStyle.theta, &w, &h, bbox);
		t = Blt_TranslatePoint(&(labelPtr->anchorPos), w, h, 
			axisPtr->tickStyle.anchor);
		t.x = x - t.x - (w * 0.5);
		t.y = y - t.y - (h * 0.5);

		bbox[4] = bbox[0];
		if (Blt_PointInPolygon(&t, bbox, 5)) {
		    axisPtr->detail = "label";
		    return axisPtr;
		}
	    }
	}
	if (axisPtr->titleText != NULL) { /* and then the title string. */
	    Point2D t;

	    Blt_GetTextExtents(&(axisPtr->titleStyle), axisPtr->titleText, 
			       &w, &h);
	    Blt_GetBoundingBox(w, h, axisPtr->titleStyle.theta, &w, &h, bbox);
	    t = Blt_TranslatePoint(&(axisPtr->titlePos), w, h, 
				axisPtr->titleStyle.anchor);
	    /* Translate the point so that the 0,0 is the upper left 
	     * corner of the bounding box.  */
	    t.x = x - t.x - (w / 2);
	    t.y = y - t.y - (h / 2);
	    
	    bbox[4] = bbox[0];
	    if (Blt_PointInPolygon(&t, bbox, 5)) {
		axisPtr->detail = "title";
		return axisPtr;
	    }
	}
	if (axisPtr->lineWidth > 0) { /* Check for the axis region */
	    if (PointInRegion(&axisPtr->region, x, y)) {
		axisPtr->detail = "line";
		return axisPtr;
	    }
	}
    }
    return NULL;
}
 
ClientData
Blt_MakeAxisTag(graphPtr, tagName)
    Graph *graphPtr;
    char *tagName;
{
    Blt_HashEntry *hPtr;
    int isNew;

    hPtr = Blt_CreateHashEntry(&(graphPtr->axes.tagTable), tagName, &isNew);
    assert(hPtr);
    return Blt_GetHashKey(&(graphPtr->axes.tagTable), hPtr);
}