File: tkRaster.c

package info (click to toggle)
staden 2.0.0%2Bb11-7
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 21,584 kB
  • sloc: ansic: 240,605; tcl: 65,360; cpp: 12,854; makefile: 11,203; sh: 3,023; fortran: 2,033; perl: 63; awk: 46
file content (3475 lines) | stat: -rw-r--r-- 101,492 bytes parent folder | download | duplicates (5)
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
/*
 * tkRaster.c --
 *
 *	This module implements "raster" widgets.  A "raster" is
 *      a rectangular array of pixels visible through a window.
 *      Commands are provided for drawing simple shapes on the
 *      raster. A raster may also have additional named pixmaps that
 *      may be used to move rectangular chunks of pixels to/from
 *      the displayed pixmap through the use of bitblt operations.
 *
 * Acknowlegment:
 *
 *   	This stuff has been mostly copied from file tkSquare.c of
 *      tk's distribution.
 *
 * Disclaimer:
 *
 *      Use this at your own risk.
 */
/* HACK - put somewhere else */
#define ROUND(x)   ((x) < 0.0 ? ceil((x) - 0.5) : floor((x) + 0.5))

#define DEF_RASTER_HEIGHT "300"
#define DEF_RASTER_WIDTH "400"
#define DEF_RASTER_BORDER_WIDTH "2"
#define DEF_RASTER_GEOMETRY (char *)NULL
#define DEF_RASTER_X_SCROLL_CMD (char*)NULL
#define DEF_RASTER_Y_SCROLL_CMD (char*)NULL
#define DEF_RASTER_STIPPLE None
#define DEF_RASTER_SCROLL_INCREMENT "10"

#define RASTER_DRAW_PIXMAP 1
#define RASTER_DRAW_BORDER 2
#define RASTER_DRAW_ALL    3


#include <stdio.h>
#include <memory.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include <float.h>
#include <math.h>
#include <tcl.h>
#include <tk.h>
#include <X11/Xlib.h>

#define HIGH INT_MAX
#define LOW INT_MIN


/* For the prototypes for our implementations of X functions */
#ifdef _WIN32
#include "tkWinX.h"
#endif


#include "tkRaster.h"
#include "tkRasterBuiltIn.h"
#include "xalloc.h"
#include "tcl_utils.h"

/*
 * A Drawing Environment is a set of arguments that affect the
 * drawing of primitives (color, line thickness, fill pattern etc). It
 * is implemented as a  XGCValues structure plus a bitmask. A raster may
 * have many of these loaded at the same time
 */
/*
typedef struct {
   XGCValues gcValues;
   unsigned long valMask;
   XColor * fgColor, * bgColor;
   int index;
} DrawEnvironment;
*/
/*
 * A data structure of the following type is kept for each Raster
 * widget managed by this file:
 */

typedef struct Raster_t {
    Tk_Window tkwin;		/* Window that embodies the Raster.  NULL
				 * means window has been deleted but
				 * widget record hasn't been cleaned up yet. */
    Display *display;		/* X's token for the window's display. */
    Tcl_Interp *interp;		/* Interpreter associated with widget. */
    int x, y;			/* Position of viewable pixmap's upper-left
				 * corner within the widget's area */

    int new_x, new_y;
    int initialised;		/* Startup: has configure finished yet */
    char * geometry;		/* This tells us the geometry that should
				   be requested for the window. If null,
				   window should be big enough to display
				   raster */

    char *xScrollCmd;		/* Command prefix for communicating with
				 * horizontal scrollbar.  NULL means no
				 * horizontal scrollbar.  Malloc'ed*/

    char *yScrollCmd;		/* Command prefix for communicating with
				 * vertical scrollbar.  NULL means no
				 * vertical scrollbar.  Malloc'ed*/

    int scrollIncrement;	/* Scroll increment units */
    int winWidth;		/* Width of window. */
    int winHeight;		/* Height of window. */

    int width;			/* Width of raster. */
    int height;                 /* Height of raster. */

    Cursor cursor;              /* Current cursor for window, or None. */

    double wx_start;            /* extents of scrolling region */
    double wy_start;            /* used in x and y scrolling */
    double wx_end;
    double wy_end;

    /*
     * GC related options
     */

    GC drawGC;			/* Graphics context for drawing */
    Tcl_HashTable drawEnvTable; /* Set of Drawing Environments currently
				   defined for this Raster */
    int drawEnvCount;		/* Number of Drawing Environments created
				   for this raster so far */
    DrawEnvironment* currentDrawEnv;
                                /* Drawing Environment currently loaded
				   in drawGC */

    /*
     * Information used when displaying widget:
     */

    int borderWidth;		/* Width of 3-D border around whole widget. */
    Tk_3DBorder bgBorder;	/* Used for drawing background. */
    XColor *fgColor;		/* For drawing visible pixmap. */
    int relief;			/* Indicates whether window as a whole is
				 * raised, sunken, or flat. */
    GC copyGC;        	        /* Graphics context for copying to screen */
    Pixmap pm;			/* Pixmap for storing the raster */
    int doubleBuffer;		/* Non-zero means double-buffer redisplay
				 * with pixmap;  zero means draw straight
				 * onto the display. */
    int updatePending;		/* Non-zero means a call to DisplayRaster
				 * has already been scheduled. */
    int x0, y0, x1, y1;		/* coordinates of rectangle of the
				   pixmap that has to be redisplayed */
    int doclip;                 /* Tells the display routine whether
				   updating the window can be done using
				   a clip mask or not. If so, the 'clip'
				   rectangle is used. */
    int cx0,cy0,cx1,cy1;	/* Clip Rectangle */

    /*
     *  Values used for World-To-Raster-And-Back transformations:
     */

    double ax, bx;     		/* rx = (int) ax * (wx - bx) */
    double ay, by;		/* ry = (int) ay * (wy - by) */
    double wx0, wy0, wx1, wy1;  /* Coords of upperleft corner and bottom right
				   corners of the "world" */

    /*
     *  Area modified when drawing a primitive
     */

    int px0, py0, px1, py1;
    int knownarea;

    /*
     *  Private storage needed for each primitive
     */

    ClientData *primitiveData;

    /*void (*plot_func)(struct Raster_t *raster, int x0, int y0, int x1, int y1); */
    void (*plot_func)(Tk_Raster *raster, char *raster_win, int job,
		      int x0, int y0, int x1, int y1);
} Raster;



/*
 * A Tcl Hash table is used to parse the built-in and user-specified
 * raster primitives. An entry value in this hash table is a pointer
 * to a RasterImplement structure.
 */

typedef struct {
   char* primitive;
   int primitiveno;
   RasterPrimDrawProc * draw;
   RasterPrimInitProc * init;
   RasterPrimFreeProc * free;
} RasterImplement;

static Tcl_HashTable PrimitiveTable;  /* Hash table for storing primitive
					 implementations */
static int PrimitiveCount = 0;	      /* Number of primitives presently
					 supported */

/*
 * Forward declarations for procedures defined later in this file:
 */

static int  ConfigureRaster _ANSI_ARGS_((Tcl_Interp *, Raster *,
					int argc, char **argv, int flags));
static void DestroyRaster _ANSI_ARGS_((char *clientData));
static void DisplayRaster _ANSI_ARGS_((ClientData clientData));
static void RasterEventProc _ANSI_ARGS_((ClientData clientData,
					 XEvent *eventPtr));
static int  RasterWidgetCmd _ANSI_ARGS_((ClientData clientData, Tcl_Interp *,
					int argc, char **argv));
static int  RasterDraw _ANSI_ARGS_((Tcl_Interp*, Raster*, RasterImplement*,
				   int argc, char ** argv));
static void arrangeDisplay _ANSI_ARGS_((Raster*, int x0, int y0,
					int x1, int y1, int type));
static void arrangeExpose _ANSI_ARGS_((Raster*, int x0, int y0,
				       int x1, int y1));
static int  myOptionParse _ANSI_ARGS_((ClientData, Tcl_Interp *,
				       Tk_Window, char*, char*, int));
static char * myOptionPrint _ANSI_ARGS_((ClientData, Tk_Window, char*,
					 int, Tcl_FreeProc ** ));

static int ConfigDrawEnv _ANSI_ARGS_((Tcl_Interp*, Raster*, DrawEnvironment*,
				      int argc, char * argv []));

static int CreateDrawEnv _ANSI_ARGS_((Tcl_Interp *, Raster*,
				      int argc,  char* argv []));
static void DestroyDrawEnv _ANSI_ARGS_((Raster*, DrawEnvironment*));
static void RasterScrollX(Raster *raster, int x, int old);
static void RasterScrollY(Raster *raster, int y, int old);
static void RasterClear(Raster *RasterPtr);

/*
 * Not implemented (by Tk) configuration options used in this widgets
 * are supported via custom options (see Tk_ConfigureWidget).
 * The parsing and printing of these options are done through procs
 * myOptionParse and myOptionPrint respectively. Those functions
 * require as a ClientData argument a table where each entry is
 * composed of a string and an associated integer value (AttrNameValue
 * below).
 */

typedef struct {
   char * optionname;
   int optionvalue;
} AttrNameValue;

AttrNameValue FillStyleTable [] = {
   { "solid", FillSolid },
   { "opaquestippled", FillOpaqueStippled },
   { "stippled", FillStippled },
   { (char*) NULL, 0 }
};

AttrNameValue LineStyleTable [] = {
   { "solid", LineSolid },
   { "doubledash", LineDoubleDash },
   { "onoffdash", LineOnOffDash },
   { (char*) NULL, 0 }
};

AttrNameValue FunctionTable [] = {
   { "clear", GXclear },
   { "and", GXand },
   { "andreverse", GXandReverse },
   { "copy", GXcopy },
   { "andinverted", GXandInverted },
   { "noop", GXnoop },
   { "xor", GXxor },
   { "or", GXor },
   { "nor", GXnor },
   { "equiv", GXequiv },
   { "invert", GXinvert },
   { "orreverse", GXorReverse },
   { "copyinverted", GXcopyInverted },
   { "orinverted", GXorInverted },
   { "nand", GXnand },
   { "set", GXset },
   { (char*) NULL, 0 }
};

Tk_CustomOption FillStyleOption = {
   myOptionParse,
   myOptionPrint,
   (ClientData) FillStyleTable
};

Tk_CustomOption LineStyleOption = {
   myOptionParse,
   myOptionPrint,
   (ClientData) LineStyleTable
};

Tk_CustomOption FunctionOption = {
   myOptionParse,
   myOptionPrint,
   (ClientData) FunctionTable
};


/*
 * Information used for argv parsing: Some config items correspond to
 * setting values in the Graphics Context structure (drawGC of Raster).
 * Depending on the type of feature being drawn (Line, Rect, etc),
 * some GC values may be reset at drawing time and reset to the
 * old values after the drawing is finished by passing appropriate
 * config options. See the code for rasterDraw below.
 */

static Tk_ConfigSpec configSpecs[] = {
    {TK_CONFIG_BORDER, "-background", "background",  "Background",
	"#d9d9d9", Tk_Offset(Raster, bgBorder),  TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_BORDER, "-background", "background", "Background",
	"white", Tk_Offset(Raster, bgBorder), TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
	"brown", Tk_Offset(Raster, fgColor), TK_CONFIG_COLOR_ONLY},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
	"black", Tk_Offset(Raster, fgColor), TK_CONFIG_MONO_ONLY},
    {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL,
	(char *) NULL, 0, 0},
    {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *) NULL,
	(char *) NULL, 0, 0},
    {TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL,
	(char *) NULL, 0, 0},
    {TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth",
	DEF_RASTER_BORDER_WIDTH, Tk_Offset(Raster, borderWidth), 0},
    {TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor",
        (char*) NULL, Tk_Offset(Raster, cursor), TK_CONFIG_NULL_OK},
    {TK_CONFIG_INT, "-dbl", "doubleBuffer", "DoubleBuffer",
	"0", Tk_Offset(Raster, doubleBuffer), 0},
    {TK_CONFIG_INT, "-x", "x", "X",
	"0", Tk_Offset(Raster, x), 0},
    {TK_CONFIG_INT, "-y", "y", "Y",
	"0", Tk_Offset(Raster, y), 0},
    {TK_CONFIG_STRING, "-geometry", "geometry", "Geometry",
	DEF_RASTER_GEOMETRY, Tk_Offset(Raster, geometry), TK_CONFIG_NULL_OK},
    {TK_CONFIG_RELIEF, "-relief", "relief", "Relief",
	"raised", Tk_Offset(Raster, relief), 0},
    {TK_CONFIG_PIXELS, "-width", "width", "Width",
	DEF_RASTER_WIDTH, Tk_Offset(Raster, width), 0},
    {TK_CONFIG_PIXELS, "-height", "height", "Height",
	DEF_RASTER_HEIGHT, Tk_Offset(Raster, height), 0},
    {TK_CONFIG_STRING, "-xscrollcommand", "xScrollCommand", "ScrollCommand",
	DEF_RASTER_X_SCROLL_CMD, Tk_Offset(Raster, xScrollCmd),
	TK_CONFIG_NULL_OK},
    {TK_CONFIG_STRING, "-yscrollcommand", "yScrollCommand", "ScrollCommand",
	DEF_RASTER_Y_SCROLL_CMD, Tk_Offset(Raster, yScrollCmd),
	TK_CONFIG_NULL_OK},
    {TK_CONFIG_PIXELS, "-scrollincrement", "scrollIncrement","ScrollIncrement",
	DEF_RASTER_SCROLL_INCREMENT, Tk_Offset(Raster, scrollIncrement), 0},
    {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL,
	(char *) NULL, 0, 0}
};



/*----------------------------------------------------------------------
 *  RasterInit --
 *
 *  	Initializes the Raster Widget module. This involves basically
 *  	setting up the built in raster primitives.
 *
 *  Results:
 *  	A standard Tcl result indicating the success of the initialization
 *
 *  Side effects:
 *	A new hash table is created.
 *----------------------------------------------------------------------
 */
int Raster_Init (Tcl_Interp *interp)
{
   Tcl_InitHashTable (&PrimitiveTable, TCL_STRING_KEYS);
   Tcl_CreateCommand(interp, "raster", RasterCmd,
		     (ClientData)Tk_MainWindow(interp),
		     NULL);
  return RasterBuiltInInit (interp);
}


/*
 *--------------------------------------------------------------
 *
 * RasterCmd --
 *
 *	This procedure is invoked to process the "Raster" Tcl
 *	command.  It creates a new "Raster" widget.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	A new widget is created and configured.
 *
 *--------------------------------------------------------------
 */

int
RasterCmd(ClientData clientData, Tcl_Interp *interp, int argc, char **argv)
{
    Tk_Window tkwin;
    Raster *RasterPtr;
    ClientData newenv;
    ClientData * dataPtr;
    Tcl_HashSearch search;
    Tcl_HashEntry* entryPtr;
    RasterImplement* primitivePtr;
    int result;

    if (argc < 2) {
	Tcl_AppendResult(interp, "wrong # args:  should be \"",
		argv[0], " pathName ?options?\"", (char *) NULL);
	return TCL_ERROR;
    }

    tkwin = Tk_CreateWindowFromPath(interp, Tk_MainWindow(interp), argv[1],
				    (char *) NULL);
    if (tkwin == NULL) {
	return TCL_ERROR;
    }
    Tk_SetClass(tkwin, "Raster");

    /*
     * Allocate and initialize the widget record.
     */

    RasterPtr = (Raster *) ckalloc(sizeof(Raster));
    RasterPtr->tkwin = tkwin;
    RasterPtr->display = Tk_Display(tkwin);
    RasterPtr->interp = interp;
    RasterPtr->x = 0;
    RasterPtr->y = 0;
    RasterPtr->new_x = 0;
    RasterPtr->new_y = 0;
    RasterPtr->width = None;
    RasterPtr->height = None;
    RasterPtr->geometry = NULL;
    RasterPtr->winWidth = None;
    RasterPtr->winHeight = None;
    RasterPtr->borderWidth = 0;
    RasterPtr->bgBorder = NULL;
    RasterPtr->fgColor = NULL;
    RasterPtr->relief = TK_RELIEF_FLAT;
    RasterPtr->cursor = None;
    RasterPtr->copyGC = None;
    RasterPtr->drawGC = None;
    RasterPtr->pm = None;
    RasterPtr->doubleBuffer = 0;
    RasterPtr->updatePending = 0;
    RasterPtr->ax = RasterPtr->ay = 1.0;
    RasterPtr->bx = RasterPtr->by = 0.0;
    RasterPtr->wx0 = RasterPtr->wx1 =
    RasterPtr->wy0 = RasterPtr->wy1 = 0.0;
    RasterPtr->xScrollCmd = NULL;
    RasterPtr->yScrollCmd = NULL;
    RasterPtr->scrollIncrement = 1;
    RasterPtr->drawEnvCount = 0;
    RasterPtr->currentDrawEnv = (DrawEnvironment*) NULL;
    RasterPtr->px0 = HIGH;
    RasterPtr->py0 = HIGH;
    RasterPtr->px1 = LOW;
    RasterPtr->py1 = LOW;
    RasterPtr->knownarea = 0;
    RasterPtr->initialised = 0;
    RasterPtr->wx_start = DBL_MAX/2;
    RasterPtr->wy_start = DBL_MAX/2;
    RasterPtr->wx_end = -DBL_MAX/2;
    RasterPtr->wy_end = -DBL_MAX/2;
    RasterPtr->plot_func = NULL;
    RasterPtr->x0 = HIGH;
    RasterPtr->y0 = HIGH;
    RasterPtr->x1 = LOW;
    RasterPtr->y1 = LOW;

    Tcl_InitHashTable (&(RasterPtr->drawEnvTable), TCL_ONE_WORD_KEYS);

    /* A new drawing environment numbered "0" must be created
       and installed with the following command */
    if (CreateDrawEnv (interp, RasterPtr, 0, (char**) NULL) != TCL_OK ||
	DrawEnvIndex (interp, RasterPtr, 0, &newenv) != TCL_OK) {
       return TCL_ERROR;
    }
    RasterPtr->currentDrawEnv = (DrawEnvironment*) newenv;

    Tk_CreateEventHandler(RasterPtr->tkwin, ExposureMask|StructureNotifyMask,
	    RasterEventProc, (ClientData) RasterPtr);
    Tcl_CreateCommand(interp, Tk_PathName(RasterPtr->tkwin), RasterWidgetCmd,
	    (ClientData) RasterPtr, NULL);
    if (ConfigureRaster(interp, RasterPtr, argc-2, argv+2, 0) != TCL_OK ||
	SetDrawEnv (interp, RasterPtr, newenv) != TCL_OK) {
	Tk_DestroyWindow(RasterPtr->tkwin);
	return TCL_ERROR;
    }

    /* Initialize primitives */
    RasterPtr->primitiveData = (ClientData*) malloc (sizeof(ClientData) *
						     PrimitiveCount);
    result = TCL_OK;
    for (entryPtr = Tcl_FirstHashEntry (&PrimitiveTable, &search);
	 entryPtr != NULL;
	 entryPtr = Tcl_NextHashEntry (&search)) {
       primitivePtr = (RasterImplement*) Tcl_GetHashValue (entryPtr);
       dataPtr = &(RasterPtr->primitiveData[primitivePtr->primitiveno]);
       if (primitivePtr->init != NULL) {
	  if ((*(primitivePtr->init)) (interp, RasterPtr, dataPtr) != TCL_OK)
	     result = TCL_ERROR;
       } else {
	   *dataPtr = (ClientData)0;
       }
    }
    if (result != TCL_OK) {
       Tk_DestroyWindow(RasterPtr->tkwin);
       return TCL_ERROR;
    }

    Tcl_SetResult(interp, Tk_PathName(RasterPtr->tkwin), TCL_STATIC);
    return TCL_OK;
}

/*----------------------------------------------------------------------
 * RasterAddPrimitive --
 *
 *  	Implements a new geometric primitive to be used in connection with
 *  	a raster
 *
 * Results:
 *
 *  	A standard tcl result
 *
 * Side effects:
 *
 *	Another entry in the PrimitiveTable is created
 *
 *----------------------------------------------------------------------
 */
int RasterAddPrimitive (interp, primitivename, drawproc, initproc, freeproc)
     Tcl_Interp * interp;
     char * primitivename;
     RasterPrimDrawProc * drawproc;
     RasterPrimInitProc * initproc;
     RasterPrimFreeProc * freeproc;
{
   int new;
   Tcl_HashEntry * entryPtr;
   RasterImplement *implemPtr;
   entryPtr = Tcl_CreateHashEntry (&PrimitiveTable, primitivename, &new);
   if (!new) {
      Tcl_AppendResult (interp, primitivename,
		       " could not be installed", (char*)NULL);
      return TCL_ERROR;
   }
   implemPtr = (RasterImplement*) malloc (sizeof (RasterImplement));
   Tcl_SetHashValue (entryPtr, implemPtr);
   implemPtr->primitive = primitivename;
   implemPtr->primitiveno = PrimitiveCount++;
   implemPtr->init = initproc;
   implemPtr->draw = drawproc;
   implemPtr->free = freeproc;
   return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * RasterWidgetCmd --
 *
 *	This procedure is invoked to process the Tcl command
 *	that corresponds to a widget managed by this module.
 *	See the user documentation for details on what it does.
 *
 * Results:
 *	A standard Tcl result.
 *
 * Side effects:
 *	See the user documentation.
 *
 *--------------------------------------------------------------
 */

static int
RasterWidgetCmd(clientData, interp, argc, argv)
    ClientData clientData;		/* Information about Raster widget. */
    Tcl_Interp *interp;			/* Current interpreter. */
    int argc;				/* Number of arguments. */
    char **argv;			/* Argument strings. */
{
    Raster *RasterPtr = (Raster *) clientData;
    int result = TCL_OK;
    int length;
    char c;
    int index;
    int rx, ry;
    double x0, x1, y0, y1;
    Tcl_HashEntry *entryPtr;
    RasterImplement * implemPtr;
    DrawEnvironment * drawEnvPtr;

    if (argc < 2) {
	Tcl_AppendResult(interp, "wrong # args: should be \"",
		argv[0], " option ?arg arg ...?\"", (char *) NULL);
	return TCL_ERROR;
    }

    Tcl_Preserve((ClientData) RasterPtr);
    c = argv[1][0];
    length = strlen(argv[1]);

    if ((c == 'c') && (strncmp(argv[1], "cget", length) == 0)) {
	/* CGET COMMAND */
	if (argc != 3) {
            Tcl_AppendResult(interp, "wrong # args: should be \"",
                    argv[0], " cget option\"",
                    (char *) NULL);
            goto error;
        }
        result = Tk_ConfigureValue(interp, RasterPtr->tkwin, configSpecs,
                (char *) RasterPtr, argv[2], 0);
    }
    else if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0)) {
        /* CONFIGURE COMMAND */
	if (argc == 2) {
	    result = Tk_ConfigureInfo(interp, RasterPtr->tkwin, configSpecs,
		    (char *) RasterPtr, (char *) NULL, 0);
	} else if (argc == 3) {
	    result = Tk_ConfigureInfo(interp, RasterPtr->tkwin, configSpecs,
		    (char *) RasterPtr, argv[2], 0);
	} else {
	    result = ConfigureRaster(interp, RasterPtr, argc-2, argv+2,
		    TK_CONFIG_ARGV_ONLY);
	}
	if (result != TCL_OK) goto error;
	arrangeDisplay (RasterPtr, LOW, LOW, HIGH, HIGH, RASTER_DRAW_ALL);
    }
    else if ((c == 'c') && (strncmp (argv [1], "clear", length) == 0)) {
       /* CLEAR COMMAND */
       if (argc != 2) {
	  Tcl_AppendResult (interp, "wrong # args: should be \"",
			    argv[0], " clear", (char *) NULL);
	  goto error;
       }
       XFillRectangle (RasterPtr->display, RasterPtr->pm, RasterPtr->copyGC,
		       0, 0, RasterPtr->width, RasterPtr->height);
       arrangeDisplay (RasterPtr, LOW, LOW, HIGH, HIGH, RASTER_DRAW_PIXMAP);
    }
    else if ((c == 'x') &&  (strncmp(argv[1], "xview", length) == 0)) {
       /* XVIEW COMMAND */
	int count, type;
	double fraction;
	double world_length = RasterPtr->wx_end - RasterPtr->wx_start;
	int win_width = Tk_Width(RasterPtr->tkwin) -
	    (2 * RasterPtr->borderWidth);

	if (argc == 2) {
/*
	    PrintScrollFractions(canvasPtr->xOrigin + canvasPtr->inset,
		    canvasPtr->xOrigin + Tk_Width(canvasPtr->tkwin)
		    - canvasPtr->inset, canvasPtr->scrollX1,
		    canvasPtr->scrollX2, interp->result);
*/
	} else {
	    type = Tk_GetScrollInfo(interp, argc, argv, &fraction, &count);
#ifdef DEBUG
	    printf("XVIEW\n");
	    printf("FRACTION %f\n", fraction);
#endif

	    switch (type) {
		case TK_SCROLL_ERROR:
		    goto error;
		case TK_SCROLL_MOVETO: {
		    double wdx;

		    //		    if (fraction <= 0)
		    //			fraction = 0;

		    wdx = RasterPtr->wx1 - RasterPtr->wx0;

#ifdef DEBUG
		    printf("world_length %f wdx %f %f\n", world_length, wdx,
			   (world_length - wdx) / world_length);
#endif
		    //		    if (fraction >= (world_length - wdx) / world_length)
		    //			fraction = (world_length - wdx) / world_length;
		    WorldToRaster(RasterPtr, (world_length * fraction +
					      RasterPtr->wx_start), 0,
				  &rx, &ry);
		    RasterPtr->new_x = rx + RasterPtr->x;
#ifdef DEBUG
		    printf("MOVETO %f %d rx %d\n", fraction,
			   RasterPtr->new_x, rx);
#endif
		    break;
		}
	    case TK_SCROLL_PAGES: {
		int rx0, ry0, rx1, ry1;
#ifdef DEBUG
		printf("scroll pages \n");
		printf("count %d \n", count);

#endif
		WorldToRaster(RasterPtr, RasterPtr->wx_start,
			      RasterPtr->wy_start, &rx0, &ry0);
		WorldToRaster(RasterPtr, RasterPtr->wx_end,
			      RasterPtr->wy_end, &rx1, &ry1);

		RasterPtr->new_x += count * .9 * win_width;

		if (rx0 - (count*.9* win_width) >= 0) {
		    RasterPtr->new_x += rx0 - (count * .9 * win_width);
		}

		if (rx1-(count*.9*win_width) <= win_width) {
		    RasterPtr->new_x += (rx1 - (count*.9*win_width) - win_width);
		}

		break;
	    }
	    case TK_SCROLL_UNITS: {
		int rx0, ry0, rx1, ry1;

		    WorldToRaster(RasterPtr, RasterPtr->wx_start,
				  RasterPtr->wy_start, &rx0, &ry0);
		    WorldToRaster(RasterPtr, RasterPtr->wx_end,
				  RasterPtr->wy_end, &rx1, &ry1);

		    if (RasterPtr->scrollIncrement > 0) {
			RasterPtr->new_x += count*RasterPtr->scrollIncrement;
		    } else {
			RasterPtr->new_x += count * .1 *
			    (Tk_Width(RasterPtr->tkwin));
		    }
#ifdef DEBUG
		    printf("SCROLL %d x %d new %d rx0 %d rx1 %d width %d\n",
			   count*RasterPtr->scrollIncrement,
			   RasterPtr->x, RasterPtr->new_x, rx0, rx1,
			   win_width);
		    printf("wx0 %f wx1 %f\n", RasterPtr->wx0, RasterPtr->wx1);
#endif
		    if (rx0 - (count*RasterPtr->scrollIncrement) >= 0) {
			RasterPtr->new_x += rx0-(count*RasterPtr->scrollIncrement);
		    }

		    if (rx1-(count*RasterPtr->scrollIncrement) <= win_width) {
			RasterPtr->new_x += (rx1 - (count*RasterPtr->scrollIncrement) - win_width);
		    }

		    break;
		}
	    }
	}

	arrangeDisplay (RasterPtr, LOW, LOW, HIGH, HIGH, RASTER_DRAW_PIXMAP);
    }
    else if ((c == 'y') &&  (strncmp(argv[1], "yview", length) == 0)) {
	/* YVIEW COMMAND */
	int count, type;
	double fraction;
	double world_height = RasterPtr->wy_end - RasterPtr->wy_start;
	int win_height = Tk_Height(RasterPtr->tkwin) -
	    (2 * RasterPtr->borderWidth);

	if (argc == 2) {
	    /*
	    PrintScrollFractions(canvasPtr->yOrigin + canvasPtr->inset,
	    canvasPtr->yOrigin + Tk_Height(canvasPtr->tkwin)
	    - canvasPtr->inset, canvasPtr->scrollY1,
	    canvasPtr->scrollY2, interp->result);
	    */

	} else {
	    type = Tk_GetScrollInfo(interp, argc, argv, &fraction, &count);
	    switch (type) {
	    case TK_SCROLL_ERROR:
		goto error;
	    case TK_SCROLL_MOVETO: {
		double wdy;

		if (fraction <= 0)
		    fraction = 0.0;

		wdy = RasterPtr->wy1 - RasterPtr->wy0;

#ifdef DEBUG
		printf("world_height %f wdy %f %f\n", world_height, wdy,
		       (world_height - wdy) / world_height);
#endif
		if (fraction >= (world_height - wdy) / world_height) {
		    fraction = (world_height - wdy) / world_height;
		}
#ifdef DEBUG
		printf("fraction %f \n", fraction);
#endif
		WorldToRaster(RasterPtr, 0, (world_height * fraction +
					     RasterPtr->wy_start),
			      &rx, &ry);
		RasterPtr->new_y = ry + RasterPtr->y;
#ifdef DEBUG
		printf("MOVETO %f %d ry %d RasterPtr->y %d\n", fraction,
		       RasterPtr->new_y, ry, RasterPtr->y);
#endif
		break;
	    }
	    case TK_SCROLL_PAGES:
		{
		    int rx0, ry0, rx1, ry1;
#ifdef DEBUG
		    printf("scroll pages \n");
#endif
		    WorldToRaster(RasterPtr, RasterPtr->wx_start,
				  RasterPtr->wy_start, &rx0, &ry0);
		    WorldToRaster(RasterPtr, RasterPtr->wx_end,
				  RasterPtr->wy_end, &rx1, &ry1);

		    RasterPtr->new_y += count * .9 * win_height;

		    if (ry0 - (count*.9* win_height) >= 0) {
			RasterPtr->new_y += ry0 - (count * .9 * win_height);
		    }

		    if (ry1-(count*.9*win_height) <= win_height) {
			RasterPtr->new_y += (ry1 - (count*.9*win_height) - win_height);
		    }
		    break;
		}
	    case TK_SCROLL_UNITS: {
		int rx0, ry0, rx1, ry1;

		WorldToRaster(RasterPtr, RasterPtr->wx_start,
			      RasterPtr->wy_start, &rx0, &ry0);
		WorldToRaster(RasterPtr, RasterPtr->wx_end,
			      RasterPtr->wy_end,
			      &rx1, &ry1);

		if (RasterPtr->scrollIncrement > 0) {
		    RasterPtr->new_y += count*RasterPtr->scrollIncrement;
		} else {
		    RasterPtr->new_y += count * .1 *
			(Tk_Height(RasterPtr->tkwin));
		}
		printf("SCROLL %d y %d new %d ry0 %d ry1 %d height %d\n",
		       count*RasterPtr->scrollIncrement,
		       RasterPtr->y, RasterPtr->new_y, ry0, ry1,
		       win_height);
		printf("wy0 %f wy1 %f\n", RasterPtr->wy0, RasterPtr->wy1);
		if (ry0 - (count*RasterPtr->scrollIncrement) >= 0) {
		    RasterPtr->new_y += ry0-(count*RasterPtr->scrollIncrement);
		    printf("NEW_Y1 %d\n", RasterPtr->new_y);
		}

		if (ry1-(count*RasterPtr->scrollIncrement) <= win_height) {
		    RasterPtr->new_y += (ry1 - (count*RasterPtr->scrollIncrement) - win_height);
		    printf("NEW_Y2 %d\n", RasterPtr->new_y);
		}

		break;
	    }
	    }
	}

	arrangeDisplay (RasterPtr, LOW, LOW, HIGH, HIGH, RASTER_DRAW_PIXMAP);
    }
    else if ((c == 'e') && (strncmp (argv [1], "envset", length) == 0)) {
       /* ENVSET COMMAND */
       if (argc > 2) {
	  if (Tcl_GetInt(RasterPtr->interp, argv[2], &index) != TCL_OK) {
	     goto error;
	  }
	  if (DrawEnvIndex (interp, RasterPtr, index,
			    (ClientData*)&drawEnvPtr) != TCL_OK){
	     goto error;
	  }
	  result = SetDrawEnv (interp, RasterPtr, drawEnvPtr);
       }
       else {
	   vTcl_SetResult(interp, "%d", RasterPtr->currentDrawEnv->index);
       }
    }
    else if ((c == 'e') && (strncmp (argv [1], "envcreate", length) == 0)) {
       /* ENVCREATE COMMAND */
       result = CreateDrawEnv (interp, RasterPtr, argc-2, argv+2);
    }
    else if ((c == 'e') && (strncmp (argv [1], "envconfigure", length) == 0)) {
       /* ENVCONFIG COMMAND */
       if (argc > 2 && isdigit(argv [2][0])) {
	  if (Tcl_GetInt(RasterPtr->interp, argv[2], &index) != TCL_OK) {
	     goto error;
	  }
	  argc -= 3;
	  argv += 3;
       }
       else {
	  index = 0;
	  argc -= 2;
	  argv += 2;
       }
       if (DrawEnvIndex (interp, RasterPtr, index,
			 (ClientData*) &drawEnvPtr) != TCL_OK) {
	  goto error;
       }
       if (argc < 2) {
	  result = ConfigInfoDrawEnv (interp, RasterPtr, drawEnvPtr,
				      argc, argv);
       } else {
	  result = ConfigDrawEnv (interp, RasterPtr, drawEnvPtr, argc, argv);
       }
    }
    else if ((c == 'e') && (strncmp (argv [1], "envdelete", length) == 0)) {
       /* ENVDELETE COMMAND */
       if (argc > 2) {
	  if (Tcl_GetInt(RasterPtr->interp, argv[2], &index) != TCL_OK) {
	     goto error;
	  }
	  if (DrawEnvIndex (interp, RasterPtr, index,
			    (ClientData*)&drawEnvPtr) != TCL_OK){
	     goto error;
	  }
       }
       else {
	  drawEnvPtr = RasterPtr->currentDrawEnv;
	  index = drawEnvPtr->index;
       }
       if (index == 0) {
	  Tcl_AppendResult (interp, "Cannot delete drawing environment 0",
			    (char*) NULL);
	  goto error;
       }
       DestroyDrawEnv (RasterPtr, drawEnvPtr);
       if (drawEnvPtr == RasterPtr->currentDrawEnv) {
	  DrawEnvIndex (interp, RasterPtr, 0, (ClientData*) &drawEnvPtr);
	  SetDrawEnv (interp, RasterPtr, drawEnvPtr);
       }
    }
    else if ((c == 'w') && (strncmp (argv [1], "world", length) == 0)) {
       /* WORLD COMMAND */
       if (argc == 2) {
	  /*return world coordinates */
	  vTcl_SetResult(interp, "%.9g %.9g %.9g %.9g",
			 RasterPtr->wx0, RasterPtr->wy0, RasterPtr->wx1,
			 RasterPtr->wy1);
       }
       else {
	  /* set world coordinates */
	  if (argc < 6) {
	     Tcl_AppendResult (interp, "wrong # args: ",
			       " expected 4 world coordinates", (char*)NULL);
	     goto error;
	  }
	  if (Tcl_GetDouble (interp, argv [2], &x0) != TCL_OK ||
	      Tcl_GetDouble (interp, argv [3], &y0) != TCL_OK ||
	      Tcl_GetDouble (interp, argv [4], &x1) != TCL_OK ||
	      Tcl_GetDouble (interp, argv [5], &y1) != TCL_OK) {
	     goto error;
	  }
	  if (x1 == x0 || y1 == y0) {
	     Tcl_AppendResult (interp, "coordinates must define a rectangle",
			       (char*) NULL);
	     goto error;
	  }
#ifdef DEBUG
	  printf("*************************WORLD*******************\n");
#endif
	  SetRasterCoords (RasterPtr, x0, y0, x1, y1);
       }
    }
    else if ((c == 'w') && (strncmp (argv [1], "world_scroll", length) == 0)) {
       /* WORLD COMMAND */
       if (argc == 2) {
	  /*return world coordinates */
	  vTcl_SetResult(interp, "%.9g %.9g %.9g %.9g",
			 RasterPtr->wx0, RasterPtr->wy0, RasterPtr->wx1,
			 RasterPtr->wy1);
       }
       else {
	  /* set world coordinates */
	  if (argc < 6) {
	     Tcl_AppendResult (interp, "wrong # args: ",
			       " expected 4 world coordinates", (char*)NULL);
	     goto error;
	  }
	  if (Tcl_GetDouble (interp, argv [2], &x0) != TCL_OK ||
	      Tcl_GetDouble (interp, argv [3], &y0) != TCL_OK ||
	      Tcl_GetDouble (interp, argv [4], &x1) != TCL_OK ||
	      Tcl_GetDouble (interp, argv [5], &y1) != TCL_OK) {
	     goto error;
	  }
	  if (x1 == x0 || y1 == y0) {
	     Tcl_AppendResult (interp, "coordinates must define a rectangle",
			       (char*) NULL);
	     goto error;
	  }
#ifdef DEBUG
	  printf("*************************WORLD*******************\n");
#endif
	  RasterSetWorldScroll (RasterPtr, x0, y0, x1, y1);
       }
    }
    else if ((c == 'w') && (strncmp (argv [1], "world_size", length) == 0)) {
	/* WORLD_SIZE COMMAND */
	/* return the total world coords of raster */

	vTcl_SetResult(interp, "%.9g %.9g %.9g %.9g",
		       RasterPtr->wx_start, RasterPtr->wy_start,
		       RasterPtr->wx_end, RasterPtr->wy_end);

    }
    else if ((c == 't') && (strncmp (argv [1], "toworld", length) == 0)) {
       /* TOWORLD COMMAND */
       if (argc < 4) {
	  Tcl_AppendResult (interp, "wrong # args: ",
			    " expected 2 raster pixmap coordinates",
			    (char*)NULL);
	  goto error;
       }
       if (Tcl_GetInt (interp, argv [2], &rx) != TCL_OK ||
	   Tcl_GetInt (interp, argv [3], &ry) != TCL_OK) {
	  goto error;
       }
/*       RasterToWorld (RasterPtr, rx - RasterPtr->x, ry - RasterPtr->y,
		      &x0, &y0);
*/
       RasterToWorld (RasterPtr, rx, ry, &x0, &y0);
#ifdef DEBUG
       printf("TOWORLD %d %d %f %f\n", rx, ry, x0, y0);
#endif
       vTcl_SetResult(interp, "%.9g %.9g", x0, y0);
    }
    else if ((c == 't') && (strncmp (argv [1], "topixmap", length) == 0)) {
       /* TOPIXMAP COMMAND */
       if (argc < 4) {
	  Tcl_AppendResult (interp, "wrong # args: ",
			    " expected 2 world coordinates",
			    (char*)NULL);
	  goto error;
       }
       if (Tcl_GetDouble (interp, argv [2], &x0) != TCL_OK ||
	   Tcl_GetDouble (interp, argv [3], &y0) != TCL_OK) {
	  goto error;
       }
       WorldToRaster (RasterPtr, x0, y0, &rx, &ry);
#ifdef DEBUG
       printf("TOPIXMAP %f %f %d %d\n", x0, y0, rx, ry);
#endif
       vTcl_SetResult(interp, "%d %d", rx, ry);
    }
    else if ((entryPtr = Tcl_FindHashEntry (&PrimitiveTable, argv[1]))
	       != NULL) {
        implemPtr = (RasterImplement*) Tcl_GetHashValue (entryPtr);
        result = RasterDraw (interp, RasterPtr, implemPtr, argc, argv);
    }
    else if ((c == 'x') && (strncmp (argv [1], "xmag", length) == 0)) {
       /* XMAG COMMAND */
	int value;
	double middle, bases;
	double wx0, wx1;
	int min_bases; /* minimum number of bases allowed */
	double base_length;
	int scale_min, scale_max;
	double scroll_length;

	scale_min = get_default_int(interp, tk_utils_defs,
				    "RASTER.SCALEX.MIN");
	scale_max = get_default_int(interp, tk_utils_defs,
				    "RASTER.SCALEX.MAX");
	min_bases = get_default_int(interp, tk_utils_defs,
				    "RASTER.SCALEX.MIN_BASES");

	if (argc < 3) {
	    Tcl_AppendResult (interp, "wrong # args: ",
			      " expected 1 scale coord",
			      (char*)NULL);
	    goto error;
	}
	if (Tcl_GetInt (interp, argv [2], &value) != TCL_OK)
	    goto error;

	if (RasterPtr->wx_end == -DBL_MAX/2 ||
	    RasterPtr->wx_start == DBL_MAX/2) {
	    Tcl_Release((ClientData) RasterPtr);
	    return result;
	}

	wx0 = RasterPtr->wx0;
	wx1 = RasterPtr->wx1;
	if (RasterPtr->wx0 < RasterPtr->wx_start) {
	    scroll_length = (double)(RasterPtr->wx1 - RasterPtr->wx0);
	    wx0 = RasterPtr->wx_start;
	    wx1 = wx0 + scroll_length;
	}

	if (RasterPtr->wx1 > RasterPtr->wx_end) {
	    scroll_length = (double)(RasterPtr->wx1 - RasterPtr->wx0);
	    wx1 = RasterPtr->wx_end;
	    wx0 = wx1 - scroll_length;
	}

	/* REAL HACK - think about this! */
	if (value == scale_min) {
	    wx1 = RasterPtr->wx_end;
	    wx0 = RasterPtr->wx_start;
	}

#ifdef DEBUG
	printf("start %f end %f wx0 %f wx1 %f\n",
	       RasterPtr->wx0, RasterPtr->wx1, wx0, wx1);
#endif

	/* middle = (double)(RasterPtr->wx1 + RasterPtr->wx0) / 2; */
	middle = (wx1 + wx0) / 2;
	base_length = RasterPtr->wx_end - RasterPtr->wx_start;
	/* base_length = wx1 - wx0; */

	bases = RasterSetXMag(interp, base_length, value);

#ifdef DEBUG
	printf("base_length %f\n", base_length);
	printf("bases %f value %d\n", bases, value);
#endif

	wx0 = middle - (bases / 2);
	wx1 = middle + (bases / 2);

#ifdef DEBUG
	printf("value %d middle %f bases %f wx0 %f wx1 %f \n",
	       value, middle, bases, wx0, wx1);
#endif
	SetRasterCoords (RasterPtr, wx0, RasterPtr->wy0, wx1, RasterPtr->wy1);
	if (RasterPtr->plot_func) {
	    /* need to round up wx1 */
	    RasterPtr->plot_func(RasterPtr, Tk_PathName(RasterPtr->tkwin),
				 RASTER_REPLOT_ALL,
				 (int)wx0, (int)RasterPtr->wy0,
				 (int)wx1+1, (int)RasterPtr->wy1);
	}
    }
    else if ((c == 'y') && (strncmp (argv [1], "ymag", length) == 0)) {
       /* YMAG COMMAND */
	double value;
	double middle, scale;
	double wy0, wy1;
	int scale_min = 1;
	double scale_length, scroll_length;

	if (argc < 3) {
	    Tcl_AppendResult (interp, "wrong # args: ",
			      " expected 1 scale coord",
			      (char*)NULL);
	    goto error;
	}
	if (Tcl_GetDouble (interp, argv [2], &value) != TCL_OK)
	    goto error;

	if (RasterPtr->wy_end == -DBL_MAX/2 ||
	    RasterPtr->wy_start == DBL_MAX/2) {
	    Tcl_Release((ClientData) RasterPtr);
	    return result;
	}

	wy0 = RasterPtr->wy0;
	wy1 = RasterPtr->wy1;
	if (RasterPtr->wy0 < RasterPtr->wy_start) {
	    scroll_length = RasterPtr->wy1 - RasterPtr->wy0;
	    wy0 = RasterPtr->wy_start;
	    wy1 = wy0 + (scroll_length);
	}

	if (RasterPtr->wy1 > RasterPtr->wy_end) {
	    scroll_length = RasterPtr->wy1 - RasterPtr->wy0;
	    wy1 = RasterPtr->wy_end;
	    wy0 = wy1 - (scroll_length);
	}

	/* REAL HACK - think about this! */
	if (value == scale_min) {
	    wy1 = RasterPtr->wy_end;
	    wy0 = RasterPtr->wy_start;
	}

#ifdef DEBUG
	printf("wy0 %f wy1 %f wy_start %f wy_end %f \n",
	        RasterPtr->wy0,  RasterPtr->wy1,  RasterPtr->wy_start,
	       RasterPtr->wy_end);

	printf("wy0 %f wy1 %f\n", wy0, wy1);
#endif
	/* middle = (double)(RasterPtr->wy1 + RasterPtr->wy0) / 2; */

	middle = (wy1 + wy0) / 2;

	scale_length = RasterPtr->wy_end - RasterPtr->wy_start;
	scale = RasterSetYMag(interp, scale_length, value);

	wy0 = middle - (scale / 2);
	wy1 = middle + (scale / 2);

#ifdef DEBUG
	printf("value %f middle %f scale %f wy0 %f wy1 %f \n",
	       value, middle, scale, wy0, wy1);
#endif

	SetRasterCoords(RasterPtr, RasterPtr->wx0, wy0, RasterPtr->wx1, wy1);

	if (RasterPtr->plot_func) {
	    RasterPtr->plot_func(RasterPtr,
				 Tk_PathName(RasterPtr->tkwin),
				 RASTER_REPLOT_ALL,
				 (int)RasterPtr->wx0, (int)wy0,
				 (int)RasterPtr->wx1, (int)wy1);
	}
    } else {
        /* OTHERS */
	Tcl_AppendResult(interp, "bad option \"", argv[1],
		"\"", (char *) NULL);
	goto error;
    }

    Tcl_Release((ClientData) RasterPtr);
    return result;

    error:
    Tcl_Release((ClientData) RasterPtr);
    return TCL_ERROR;
}

/*
 *______________________________________________________________________
 *
 * RasterDraw --
 *
 *	This procedure is invoked by RasterWidgetCmd to draw shapes
 *      on the pixmap.
 *
 * Results:
 *	A standart Tcl result
 *
 * Side effects:
 *	An appropriate thing is drawn
 *
 *----------------------------------------------------------------------
 */

static int
RasterDraw (interp, RasterPtr, implemPtr, argc, argv)
     Tcl_Interp * interp;
     Raster* RasterPtr;
     RasterImplement* implemPtr;
     int argc;
     char ** argv;
{
   RasterPtr->px0 = HIGH;
   RasterPtr->py0 = HIGH;
   RasterPtr->px1 = LOW;
   RasterPtr->py1 = LOW;
   RasterPtr->knownarea = 0;

   if ((*(implemPtr->draw)) (interp, RasterPtr,
			     RasterPtr->primitiveData [implemPtr->primitiveno],
			     argc, argv) != TCL_OK) {
      return TCL_ERROR;
   }

   if (RasterPtr->knownarea) {
      /* Primitive informed modified area of pixmap */
      if (RasterPtr->px1 >= 0 && RasterPtr->py1 >= 0) {
	 /* No point in redisplaying an empty area */
	 arrangeDisplay (RasterPtr, RasterPtr->px0, RasterPtr->py0,
			 RasterPtr->px1, RasterPtr->py1,
			 RASTER_DRAW_PIXMAP);
      }
   }
   else {
      /* Redisplay the whole pixmap */
      arrangeDisplay(RasterPtr, 0, 0, RasterPtr->width-1, RasterPtr->height-1,
		     RASTER_DRAW_PIXMAP);
   }

   return TCL_OK;
}

static void
ResizeRaster(Raster *RasterPtr,
	     int wid,
	     int hgt)
{

    Pixmap newpm;
#ifdef DEBUG
    printf("ResizeRaster\n");
#endif
    /* 7/1/99 johnt - changed X Pixmap functions to TK functions for Windows portability */
    newpm = Tk_GetPixmap (RasterPtr->display,
			   RootWindowOfScreen (Tk_Screen (RasterPtr->tkwin)),
			   RasterPtr->width, RasterPtr->height,
			   DefaultDepthOfScreen(Tk_Screen(RasterPtr->tkwin)));

    XFillRectangle (RasterPtr->display, newpm, RasterPtr->copyGC,
		    0, 0, RasterPtr->width, RasterPtr->height);
    XCopyArea (RasterPtr->display, RasterPtr->pm, newpm,
	       RasterPtr->copyGC, 0, 0, wid - RasterPtr->borderWidth,
	       hgt - RasterPtr->borderWidth, 0, 0);
    Tk_FreePixmap (RasterPtr->display, RasterPtr->pm);
    RasterPtr->pm = newpm;

    if (RasterPtr->plot_func) {
	/* HACK - is this the best place to put these? */
	RasterClear(RasterPtr);

	/* set world coords because raster height and width have changed */
	SetRasterCoords(RasterPtr, RasterPtr->wx0, RasterPtr->wy0,
			RasterPtr->wx1, RasterPtr->wy1);

	RasterPtr->plot_func(RasterPtr, Tk_PathName(RasterPtr->tkwin),
			     RASTER_REPLOT_SLIVER,
			     RasterPtr->wx_start, RasterPtr->wy_start,
			     RasterPtr->wx_end, RasterPtr->wy_end);
    }
}

/*
 *----------------------------------------------------------------------
 *
 * ConfigureRaster --
 *
 *	This procedure is called to process an argv/argc list in
 *	conjunction with the Tk option database to configure (or
 *	reconfigure) a Raster widget.
 *
 * Results:
 *	The return value is a standard Tcl result.  If TCL_ERROR is
 *	returned, then interp->result contains an error message.
 *
 * Side effects:
 *	Configuration information, such as colors, border width,
 *	etc. get set for RasterPtr;  old resources get freed,
 *	if there were any.
 *
 *----------------------------------------------------------------------
 */

static int
ConfigureRaster(interp, RasterPtr, argc, argv, flags)
    Tcl_Interp *interp;			/* Used for error reporting. */
    Raster *RasterPtr;			/* Information about widget. */
    int argc;				/* Number of valid entries in argv. */
    char **argv;			/* Arguments. */
    int flags;				/* Flags to pass to
					 * Tk_ConfigureWidget. */
{
   XGCValues gcValues;
   unsigned long valuemask;

    if (Tk_ConfigureWidget(interp, RasterPtr->tkwin, configSpecs,
	    argc, argv, (char *) RasterPtr, flags) != TCL_OK) {
	return TCL_ERROR;
    }

    /*
     *  Check width and height for reasonable values
     */

    if (RasterPtr->width < 1 || RasterPtr->width > 4096) {
       Tcl_AppendResult (interp, "Illegal raster width", (char*)NULL);
       return TCL_ERROR;
    }

    if (RasterPtr->height < 1 || RasterPtr->height > 4096) {
       Tcl_AppendResult (interp, "Illegal raster height", (char*)NULL);
       return TCL_ERROR;
    }

    /*
     * Set the background for the window and create a graphics context
     * for use during redisplay and another for drawing on the pixmap
     */

    Tk_SetWindowBackground (RasterPtr->tkwin,
			    Tk_3DBorderColor(RasterPtr->bgBorder)->pixel);


    if (RasterPtr->copyGC == None) {
       valuemask = GCFunction|GCGraphicsExposures|GCForeground;
       gcValues.function = GXcopy;
       gcValues.graphics_exposures = False;
       gcValues.foreground = Tk_3DBorderColor(RasterPtr->bgBorder)->pixel;
       RasterPtr->copyGC = Tk_GetGC(RasterPtr->tkwin,valuemask, &gcValues);
    }

    if (RasterPtr->drawGC == None) {
       valuemask = GCFunction|GCGraphicsExposures|GCForeground|GCBackground;
       gcValues.function = GXcopy;
       gcValues.background = Tk_3DBorderColor(RasterPtr->bgBorder)->pixel;
       gcValues.foreground = RasterPtr->fgColor->pixel;
       gcValues.graphics_exposures = False;
       RasterPtr->drawGC = XCreateGC (RasterPtr->display,
				      RootWindowOfScreen (
					     Tk_Screen (RasterPtr->tkwin)),
				      valuemask, &gcValues);
    }

    /*
     * Create a pixmap for storing the raster
     */
    if (RasterPtr->pm == None) {
       /* 7/1/99 johnt - changed X Pixmap functions to TK functions for Windows portability */
       RasterPtr->pm = Tk_GetPixmap (RasterPtr->display,
				      RootWindowOfScreen (
					    Tk_Screen (RasterPtr->tkwin)),
				      RasterPtr->width, RasterPtr->height,
				      DefaultDepthOfScreen(Tk_Screen(
						      RasterPtr->tkwin)));
       XFillRectangle (RasterPtr->display, RasterPtr->pm, RasterPtr->copyGC,
		       0, 0, RasterPtr->width, RasterPtr->height);
    }
    else {
       /* See if pixmap needs to be resized */
       unsigned int wid, hgt, udummy;
       int idummy;
       Window wdummy;
       XGetGeometry (RasterPtr->display, RasterPtr->pm, &wdummy,
		     &idummy, &idummy, &wid, &hgt, &udummy, &udummy);
       if (wid != RasterPtr->width || hgt != RasterPtr->height) {
#ifdef DEBUG
	  printf("Resize to %d x %d width %d height %d\n", wid, hgt,
		 RasterPtr->width, RasterPtr->height);
#endif
	  ResizeRaster(RasterPtr, wid, hgt);
/*
	  Pixmap newpm = XCreatePixmap (RasterPtr->display,
	      RootWindowOfScreen (Tk_Screen (RasterPtr->tkwin)),
	      RasterPtr->width, RasterPtr->height,
	      DefaultDepthOfScreen(Tk_Screen(RasterPtr->tkwin)));
	  XFillRectangle (RasterPtr->display, newpm, RasterPtr->copyGC,
			  0, 0, RasterPtr->width, RasterPtr->height);
	  XCopyArea (RasterPtr->display, RasterPtr->pm, newpm,
		     RasterPtr->copyGC, 0, 0, wid, hgt, 0, 0);
	  XFreePixmap (RasterPtr->display, RasterPtr->pm);
	  RasterPtr->pm = newpm;
*/
       }
    }


    /*
     * If geometry was specified, take this as the intended size for the
     * window through which the raster will be viewed. otherwise, try to
     * get a window large enough for the raster plus the border
     */
    if (RasterPtr->geometry == NULL) {
       RasterPtr->winWidth = RasterPtr->width+2*RasterPtr->borderWidth;
       RasterPtr->winHeight = RasterPtr->height+2*RasterPtr->borderWidth;
    }
    else {
       int h, w;
       if (sscanf (RasterPtr->geometry, "%dx%d", &h, &w) != 2) {
	  Tcl_AppendResult(interp, "bad geometry \"", RasterPtr->geometry,
			   "\": expected widthxheight", (char *) NULL);
	  return TCL_ERROR;
       }
       RasterPtr->winWidth = w;
       RasterPtr->winHeight = h;
    }

    RasterPtr->initialised = 1;

    /*
     * Register the desired geometry for the window.  Then arrange for
     * the window to be redisplayed.
     */
    Tk_GeometryRequest(RasterPtr->tkwin,
		       RasterPtr->winWidth,
		       RasterPtr->winHeight);
    Tk_SetInternalBorder(RasterPtr->tkwin, RasterPtr->borderWidth);
    arrangeDisplay (RasterPtr, LOW, LOW, HIGH, HIGH, RASTER_DRAW_ALL);

#ifdef DEBUG
    printf("winheight %d \n", RasterPtr->winHeight);
#endif
    return TCL_OK;
}

/*
 *--------------------------------------------------------------
 *
 * RasterEventProc --
 *
 *	This procedure is invoked by the Tk dispatcher for various
 *	events on Rasters.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	When the window gets deleted, internal structures get
 *	cleaned up.  When it gets exposed, it is redisplayed.
 *
 *--------------------------------------------------------------
 */

static void
RasterEventProc(clientData, eventPtr)
    ClientData clientData;	/* Information about window. */
    XEvent *eventPtr;		/* Information about event. */
{
   Raster *RasterPtr = (Raster *) clientData;

   if (!RasterPtr->initialised)
       return;

   if (eventPtr->type == Expose) {
      if (eventPtr->xexpose.count >= 0) {
	 arrangeExpose (RasterPtr, eventPtr->xexpose.x, eventPtr->xexpose.y,
			eventPtr->xexpose.x+eventPtr->xexpose.width,
			eventPtr->xexpose.y+eventPtr->xexpose.height);
      }
   } else if (eventPtr->type == ConfigureNotify) {
/*
       int wid = RasterPtr->width;
       int hgt = RasterPtr->height;
*/
       unsigned int wid, hgt, udummy;
       int idummy;
       Window wdummy;
       XGetGeometry (RasterPtr->display, RasterPtr->pm, &wdummy,
		     &idummy, &idummy, &wid, &hgt, &udummy, &udummy);
#ifdef DEBUG
       printf("old %d\n", RasterPtr->height);
#endif
#if 1
       RasterPtr->width = Tk_Width(RasterPtr->tkwin);
       RasterPtr->height = Tk_Height(RasterPtr->tkwin);
#ifdef DEBUG
       printf("Resize to %d x %d (%d x %d)\n", wid, hgt,
	    RasterPtr->width, RasterPtr->height);
#endif
       ResizeRaster(RasterPtr, wid, hgt);
#else
       RasterPtr->width = wid;
       RasterPtr->height = hgt;
       ResizeRaster(RasterPtr,
		    Tk_Width(RasterPtr->tkwin),
		    Tk_Height(RasterPtr->tkwin));
#endif

#ifdef DEBUG
       printf("new %d\n", RasterPtr->height);
#endif
      arrangeDisplay (RasterPtr, LOW, LOW, HIGH, HIGH, RASTER_DRAW_ALL);
   } else if (eventPtr->type == DestroyNotify) {
      Tcl_DeleteCommand(RasterPtr->interp, Tk_PathName(RasterPtr->tkwin));
      RasterPtr->tkwin = NULL;
      if (RasterPtr->updatePending) {
	 Tcl_CancelIdleCall(DisplayRaster, (ClientData) RasterPtr);
      }
      Tcl_EventuallyFree((ClientData) RasterPtr, DestroyRaster);
   }
}

/*
 *--------------------------------------------------------------
 *
 * DisplayRaster --
 *
 *	This procedure redraws the contents of a Raster window.
 *	It is invoked as a do-when-idle handler, so it only runs
 *	when there's nothing else for the application to do.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Information appears on the screen.
 *
 *--------------------------------------------------------------
 */

static void DisplayRaster(ClientData clientData)
{
    Raster *RasterPtr = (Raster *) clientData;
    Tk_Window tkwin = RasterPtr->tkwin;
    Pixmap pm = None;
    Drawable d;
    int result, winwid, winhgt, wid, hgt;
    XRectangle clip;
    int mode = RasterPtr->updatePending;
    int scrolling = 0;

#ifdef DEBUG
    printf("DisplayRaster update %d\n", RasterPtr->updatePending);
    printf("0:old=%d,%d new=%d,%d\n",
	   RasterPtr->x,RasterPtr->y,
	   RasterPtr->new_x,RasterPtr->new_y);
#endif
    RasterPtr->updatePending = 0;
    if (tkwin == NULL || !Tk_IsMapped(tkwin)) {
	return;
    }

#if 0
    /*
     * Analyze the Raster's redisplay rectangle. If we're not asked to
     * redisplay the whole pixmap then do a quick and dirty job.
     */
    if (RasterPtr->x0 > 0 || RasterPtr->y0 > 0 ||
	RasterPtr->x1 <= RasterPtr->width ||
	RasterPtr->y1 <= RasterPtr->height) {

       winx = RasterPtr->x + RasterPtr->borderWidth + RasterPtr->x0;
       winy = RasterPtr->y + RasterPtr->borderWidth + RasterPtr->y0;

       if (winx < RasterPtr->borderWidth) {
	  RasterPtr->x0 += RasterPtr->borderWidth - winx;
	  winx = RasterPtr->borderWidth;
       }
       if (winy < RasterPtr->borderWidth) {
	  RasterPtr->y0 += RasterPtr->borderWidth - winy;
	  winy = RasterPtr->borderWidth;
       }
       winwid = Tk_Width (tkwin) - 2*RasterPtr->borderWidth;
       winhgt = Tk_Height (tkwin) - 2*RasterPtr->borderWidth;
       if (RasterPtr->x1 + RasterPtr->x > winwid) {
	  RasterPtr->x1 = winwid - RasterPtr->x;
       }
       if (RasterPtr->y1 + RasterPtr->y > winhgt) {
	  RasterPtr->y1 = winhgt - RasterPtr->y;
       }
       wid = RasterPtr->x1 - RasterPtr->x0;
       hgt = RasterPtr->y1 - RasterPtr->y0;
       if (wid > 0 && hgt > 0) {
	  XCopyArea (Tk_Display(tkwin), RasterPtr->pm, Tk_WindowId(tkwin),
		     RasterPtr->copyGC,
		     RasterPtr->x0, RasterPtr->y0, wid, hgt,
		     RasterPtr->x0, RasterPtr->y0);
       }
       RasterPtr->x0 = HIGH;
       RasterPtr->y0 = HIGH;
       RasterPtr->x1 = LOW;
       RasterPtr->y1 = LOW;
       return;
    }
#endif

    /*
     * Create a pixmap for double-buffering, if necessary.
     */

    if (RasterPtr->doubleBuffer) {
	/* 7/1/99 johnt - changed X Pixmap functions to TK functions for Windows portability */
	pm = Tk_GetPixmap(Tk_Display(tkwin), Tk_WindowId(tkwin),
			   Tk_Width(tkwin), Tk_Height(tkwin),
			   DefaultDepthOfScreen(Tk_Screen(tkwin)));
	d = pm;
    } else {
	d = Tk_WindowId(tkwin);
    }

    /*
     * Set a clipping region if applicable
     */

    if (RasterPtr->doclip) {
       clip.x = RasterPtr->cx0;
       clip.y = RasterPtr->cy0;
       clip.width = RasterPtr->cx1-RasterPtr->cx0;
       clip.height = RasterPtr->cy1-RasterPtr->cy0;
       XSetClipRectangles (Tk_Display(tkwin), RasterPtr->copyGC, 0, 0,
			   &clip, 1, Unsorted);
    }

    if (mode & RASTER_DRAW_BORDER) {
	/*
	 * Redraw the widget's background and border.
	 */
	Tk_Draw3DRectangle(tkwin, d, RasterPtr->bgBorder,
			   0, 0, Tk_Width(tkwin), Tk_Height(tkwin),
			   RasterPtr->borderWidth, RasterPtr->relief);
    }

    if (mode & RASTER_DRAW_PIXMAP) {
	/*
	 * Display the Raster.
	 */
	wid = RasterPtr->width;
	hgt = RasterPtr->height;

	/* scrolling */
	if (RasterPtr->new_x != RasterPtr->x ||
	    RasterPtr->new_y != RasterPtr->y) {
	    int dx, dy;

	    /* initialise */
	    if (RasterPtr->plot_func) {
		RasterPtr->plot_func(RasterPtr, Tk_PathName(RasterPtr->tkwin),
				     RASTER_INIT,
				     RasterPtr->wx_start, RasterPtr->wy_start,
				     RasterPtr->wx_end, RasterPtr->wy_end);
	    }

	    scrolling = 1;
	    dx = RasterPtr->new_x - RasterPtr->x;
	    dy = RasterPtr->new_y - RasterPtr->y;

#ifdef DEBUG
	    printf("1:old=%d,%d new=%d,%d\n",
		   RasterPtr->x,RasterPtr->y,
		   RasterPtr->new_x,RasterPtr->new_y);
	    printf("dx %d wid %d wid-dx %d\n", dx, wid, wid-dx);
#endif
	    /* FIXME: - overflow in XCopyArea? */
	    /* width & height (wid-dx, hgt) are of type unsigned int */
	    /* only scroll in x if need to */
	    if (RasterPtr->new_x != RasterPtr->x) {
		if (RasterPtr->new_x > RasterPtr->x) {
		    if (wid > dx) {
#ifdef DEBUG
			printf("XCopyArea %d %d %d %d\n", dx, 0, wid-dx, hgt);
#endif
			/* Copying right chunk to left, clear right edge */
			XCopyArea (Tk_Display(tkwin), RasterPtr->pm,
				   RasterPtr->pm, RasterPtr->copyGC,
				   dx, 0,
				   wid - dx, hgt,
				   0, 0);
		    }
#ifdef DEBUG
		    printf("XFillRec %d %d %d %d\n",
			   wid - dx < 0 ? 0 : wid - dx, 0, wid, hgt);
#endif
		    XFillRectangle (RasterPtr->display, RasterPtr->pm,
				    RasterPtr->copyGC,
				    wid - dx < 0 ? 0 : wid - dx, 0,
				    wid, hgt);
		} else if (RasterPtr->new_x <= RasterPtr->x){

		    /* Copying left chunk to right, clear left edge */
		    if (wid + dx > 0) {
			XCopyArea (Tk_Display(tkwin), RasterPtr->pm,
				   RasterPtr->pm, RasterPtr->copyGC,
				   0, 0,
				   wid + dx, hgt,
				   -dx, 0);
		    }
		    XFillRectangle (RasterPtr->display, RasterPtr->pm,
				    RasterPtr->copyGC,
				    0, 0,
				    -dx > wid ? wid : -dx, hgt);
		}
		RasterScrollX(RasterPtr, RasterPtr->new_x, RasterPtr->x);
	    }
	    /* only scroll in y if need to */
	    if (RasterPtr->new_y != RasterPtr->y) {
		if (RasterPtr->new_y > RasterPtr->y) {
		    /* Copying bottom chunk to top, clear bottom edge */
		    XCopyArea (Tk_Display(tkwin), RasterPtr->pm, RasterPtr->pm,
			       RasterPtr->copyGC,
			       0, dy,
			       wid, hgt - dy,
			       0, 0);

		    XFillRectangle (RasterPtr->display, RasterPtr->pm,
				    RasterPtr->copyGC,
				    0, hgt - dy < 0 ? 0 : hgt - dy,
				    wid, hgt);
		} else if (RasterPtr->new_y <= RasterPtr->y){
		    /* Copying top chunk to bottom, clear top edge */
		    XCopyArea (Tk_Display(tkwin), RasterPtr->pm, RasterPtr->pm,
			       RasterPtr->copyGC,
			       0, 0,
			       wid, hgt + dy,
			       0, -dy);

		    XFillRectangle (RasterPtr->display, RasterPtr->pm,
				    RasterPtr->copyGC,
				    0, 0,
				    wid, -dy > hgt ? hgt : -dy);
		}
		RasterScrollY(RasterPtr, RasterPtr->new_y, RasterPtr->y);
#ifdef DEBUG
		printf("after scrolling \n");
#endif
	    }
	}
	winwid = Tk_Width (tkwin) - 2*RasterPtr->borderWidth;
	winhgt = Tk_Height (tkwin) - 2*RasterPtr->borderWidth;
	if (wid > 0 && hgt > 0) {
	    XCopyArea (Tk_Display(tkwin), RasterPtr->pm, d, RasterPtr->copyGC,
		       0, 0, winwid, winhgt,
		       RasterPtr->borderWidth, RasterPtr->borderWidth);
	}

	/*
	 * If double-buffered, copy to the screen and release the pixmap.
	 */

	if (RasterPtr->doubleBuffer) {
	    XCopyArea(Tk_Display(tkwin), pm, Tk_WindowId(tkwin),
		      RasterPtr->copyGC,
		      0, 0, Tk_Width(tkwin), Tk_Height(tkwin), 0, 0);
	    /* 7/1/99 johnt - changed X Pixmap functions to TK functions for Windows portability */
	    Tk_FreePixmap(Tk_Display(tkwin), pm);
	}
    }

    RasterPtr->x0 = HIGH;
    RasterPtr->y0 = HIGH;
    RasterPtr->x1 = LOW;
    RasterPtr->y1 = LOW;

    /*
     * Reset the clipping stuff
     */
    if (RasterPtr->doclip) {
       RasterPtr->doclip = 0;
       XSetClipMask (Tk_Display (tkwin), RasterPtr->copyGC, None);
    }

    RasterPtr->x = RasterPtr->new_x;
    RasterPtr->y = RasterPtr->new_y;

    if (/*scrolling &&*/ RasterPtr->xScrollCmd != NULL) {
       char args [200];
       double world_length = RasterPtr->wx_end - RasterPtr->wx_start;

#ifdef DEBUG_DISPLAY
       printf("scroll wx0 %f wx1 %f %f %f %f\n", RasterPtr->wx0,
	      RasterPtr->wx1,
	      (RasterPtr->wx0 - RasterPtr->wx_start)/ world_length,
	      (RasterPtr->wx1 - RasterPtr->wx_start)/ world_length,
	      world_length);
#endif
       sprintf(args, " %.20f %.20f",
	       (RasterPtr->wx0 - RasterPtr->wx_start) / world_length,
	       (RasterPtr->wx1 - RasterPtr->wx_start) / world_length);

       result = Tcl_VarEval (RasterPtr->interp, RasterPtr->xScrollCmd,
			     args, (char*) NULL);

       if (result != TCL_OK) {
	  Tcl_BackgroundError (RasterPtr->interp);
       }
       Tcl_ResetResult (RasterPtr->interp);

    }

    if (/*scrolling &&*/ RasterPtr->yScrollCmd != NULL) {
       char args [200];
       double world_height = RasterPtr->wy_end - RasterPtr->wy_start;

#ifdef DEBUG_DISPLAY
       printf("start %f end %f height %f\n", RasterPtr->wy_start, RasterPtr->wy_end,
	      world_height);

       printf("scroll wy0 %f wy1 %f %f %f %f \n",
	      RasterPtr->wy0, RasterPtr->wy1,
	      (RasterPtr->wy0- RasterPtr->wy_start) / world_height,
	      (RasterPtr->wy1- RasterPtr->wy_start) / world_height,
	      world_height);
#endif
       sprintf(args, " %.20f %.20f",
	       (RasterPtr->wy0 - RasterPtr->wy_start) / world_height,
	       (RasterPtr->wy1 - RasterPtr->wy_start) / world_height);


       result = Tcl_VarEval (RasterPtr->interp, RasterPtr->yScrollCmd,
			     args, (char*) NULL);
       if (result != TCL_OK) {
	  Tcl_BackgroundError (RasterPtr->interp);
       }
       Tcl_ResetResult (RasterPtr->interp);
    }

#ifdef DEBUG
    printf("2:old=%d,%d new=%d,%d\n",
	   RasterPtr->x,RasterPtr->y,
	   RasterPtr->new_x,RasterPtr->new_y);
#endif
}

/*
 *----------------------------------------------------------------------
 *
 * DestroyRaster --
 *
 *	This procedure is invoked by Tcl_EventuallyFree or Tcl_Release
 *	to clean up the internal structure of a Raster at a safe time
 *	(when no-one is using it anymore).
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Everything associated with the Raster is freed up.
 *
 *----------------------------------------------------------------------
 */

static void
DestroyRaster(char *clientData)
{
    Raster *RasterPtr = (Raster *) clientData;
    ClientData * dataPtr;
    Tcl_HashSearch search;
    Tcl_HashEntry* entryPtr;
    RasterImplement* primitivePtr;
    DrawEnvironment* drawEnvPtr;

    /* Free primitives */
    for (entryPtr = Tcl_FirstHashEntry (&PrimitiveTable, &search);
	 entryPtr != NULL;
	 entryPtr = Tcl_NextHashEntry (&search)) {
       primitivePtr = (RasterImplement*) Tcl_GetHashValue (entryPtr);
       if (primitivePtr->free != NULL) {
	  dataPtr = &(RasterPtr->primitiveData[primitivePtr->primitiveno]);
	  (*(primitivePtr->free)) (RasterPtr, *dataPtr);
       }
    }
    free (RasterPtr->primitiveData);

    /* Free DrawEnvironments */
    for (entryPtr = Tcl_FirstHashEntry (&RasterPtr->drawEnvTable, &search);
	 entryPtr != NULL;
	 entryPtr = Tcl_NextHashEntry (&search)) {
       drawEnvPtr = (DrawEnvironment*) Tcl_GetHashValue (entryPtr);
       DestroyDrawEnv (RasterPtr, drawEnvPtr);
    }
    Tcl_DeleteHashTable (&RasterPtr->drawEnvTable);

    /* Free Conf Options */
    Tk_FreeOptions(configSpecs, (char *) RasterPtr, RasterPtr->display, 0);

    /* Free X resources */
    if (RasterPtr->copyGC != None) {
	Tk_FreeGC(RasterPtr->display, RasterPtr->copyGC);
	XFreeGC (RasterPtr->display, RasterPtr->drawGC);
    }
    if (RasterPtr->pm != None) {
       /* 7/1/99 johnt - changed X Pixmap functions to TK functions for Windows portability */
       Tk_FreePixmap (RasterPtr->display, RasterPtr->pm);
    }
    ckfree((char *) RasterPtr);
}


/*=============================================================================
 */

void RasterRefresh(Raster *RasterPtr) {
   if (RasterPtr->knownarea) {
      /* Primitive informed modified area of pixmap */
      if (RasterPtr->px1 >= 0 && RasterPtr->py1 >= 0) {
	 /* No point in redisplaying an empty area */
	 arrangeDisplay (RasterPtr, RasterPtr->px0, RasterPtr->py0,
			 RasterPtr->px1, RasterPtr->py1,
			 RASTER_DRAW_PIXMAP);
      }
   }
   else {
      /* Redisplay the whole pixmap */
      arrangeDisplay(RasterPtr, 0, 0, RasterPtr->width-1, RasterPtr->height-1,
		     RASTER_DRAW_PIXMAP);
   }

   RasterPtr->px0 = HIGH;
   RasterPtr->py0 = HIGH;
   RasterPtr->px1 = LOW;
   RasterPtr->py1 = LOW;
   RasterPtr->knownarea = 0;
}

void tk_RasterRefresh(Tk_Raster *rasterptr)
{
   Raster* RasterPtr = (Raster*) rasterptr;

   RasterRefresh(RasterPtr);
}

/*
 *______________________________________________________________________
 *
 * arrangeDisplay --
 *
 *	This procedure is invoked whenever we discover that a part of
 *      the pixmap has been modified and/or a part of the window must
 *      be redrawn.
 *
 * Results:
 *
 *	None.
 *
 * Side effects:
 *
 *      A Call to DisplayRaster is eventually scheduled. The Raster
 *      structure pointed to by RasterPtr is updatedd to reflect the
 *      area that must be redisplayed.
 *
 *----------------------------------------------------------------------
 */

static void
arrangeDisplay (RasterPtr, x0, y0, x1, y1, type)
     Raster * RasterPtr;
     int x0, y0, x1, y1, type;
{
#ifdef DEBUG
    printf("arrangeDisplay update %d type %d\n", RasterPtr->updatePending,
	   type);
#endif
   RasterPtr->doclip = 0;
   if (x0 < RasterPtr->x0) RasterPtr->x0 = x0;
   if (y0 < RasterPtr->y0) RasterPtr->y0 = y0;
   if (x1 > RasterPtr->x1) RasterPtr->x1 = x1;
   if (y1 > RasterPtr->y1) RasterPtr->y1 = y1;
   if (!RasterPtr->updatePending) {
       Tcl_DoWhenIdle(DisplayRaster, (ClientData) RasterPtr);
   }
   RasterPtr->updatePending |= type;
}

/*
 *______________________________________________________________________
 *
 * arrangeExpose --
 *
 *	This procedure is invoked when we get an Expose event. It
 * 	arranges for the redisplay routine to be invoked using a
 *  	clip region constraining it to the exposed part of the window.
 *
 * Results:
 *
 *	None.
 *
 * Side effects:
 *
 *      A Call to DisplayRaster is eventually scheduled. The Raster
 *      structure pointed to by RasterPtr is updated to reflect the
 *      area that must be redisplayed.
 *
 *----------------------------------------------------------------------
 */

static void
arrangeExpose (RasterPtr, x0, y0, x1, y1)
     Raster * RasterPtr;
     int x0, y0, x1, y1;
{

#ifdef DEBUG
    printf("arrangeExpose update %d clip %d \n", RasterPtr->updatePending,
	   RasterPtr->doclip);
#endif
    if (RasterPtr->updatePending) {
	if (RasterPtr->doclip) {
	    /* Extend the clipping rectangle */
	    if (x0 < RasterPtr->cx0) RasterPtr->cx0 = x0;
	    if (y0 < RasterPtr->cy0) RasterPtr->cy0 = y0;
	    if (x1 > RasterPtr->cx1) RasterPtr->cx1 = x1;
	    if (y1 > RasterPtr->cy1) RasterPtr->cy1 = y1;
	}
	RasterPtr->x0 = RasterPtr->y0 = LOW;
	RasterPtr->x1 = RasterPtr->y1 = HIGH;
    } else {
	RasterPtr->doclip = 1;
	RasterPtr->cx0 = x0;
	RasterPtr->cy0 = y0;
	RasterPtr->cx1 = x1;
	RasterPtr->cy1 = y1;
	RasterPtr->x0 = RasterPtr->y0 = LOW;
	RasterPtr->x1 = RasterPtr->y1 = HIGH;
	Tcl_DoWhenIdle(DisplayRaster, (ClientData) RasterPtr);
    }
    RasterPtr->updatePending = RASTER_DRAW_ALL;
}

/*--------------------------------------------------------------------------
 *
 *  Configuration options for a Raster "Drawing Environment"
 */

Tk_ConfigSpec DrawEnvSpecs [] = {

    /*
    {TK_CONFIG_INT, "-bgpixel", "bgpixel",  "Bgpixel",
     (char*) NULL, Tk_Offset(DrawEnvironment, bgColor->pixel), 0},
    {TK_CONFIG_INT, "-fgpixel", "fgpixel",  "Fgpixel",
     (char*) NULL, Tk_Offset(DrawEnvironment, fgColor->pixel), 0},
     */
    {TK_CONFIG_COLOR, "-background", "background",  "Background",
	NULL, Tk_Offset(DrawEnvironment, bgColor),  TK_CONFIG_NULL_OK},
    {TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
	NULL, Tk_Offset(DrawEnvironment, fgColor), TK_CONFIG_NULL_OK},
    {TK_CONFIG_PIXELS, "-linewidth", "linewidth", "LineWidth", (char*) NULL,
	Tk_Offset(DrawEnvironment, gcValues.line_width), 0 },
    {TK_CONFIG_CUSTOM, "-linestyle", "linestyle", "LineStyle", "solid",
	Tk_Offset(DrawEnvironment, gcValues.line_style),
	TK_CONFIG_DONT_SET_DEFAULT, &LineStyleOption },
    {TK_CONFIG_CAP_STYLE, "-capstyle", "capstyle", "CapStyle",(char*) NULL,
	Tk_Offset(DrawEnvironment, gcValues.cap_style), 0},
    {TK_CONFIG_JOIN_STYLE, "-joinstyle", "joinstyle","JoinStyle",(char*) NULL,
	Tk_Offset(DrawEnvironment, gcValues.join_style), 0},
    {TK_CONFIG_CUSTOM, "-function", "function", "Function", "copy",
	Tk_Offset(DrawEnvironment, gcValues.function),
	TK_CONFIG_DONT_SET_DEFAULT, &FunctionOption },
    {TK_CONFIG_BITMAP, "-stipple", "stipple", "Stipple", (char*) NULL,
	Tk_Offset(DrawEnvironment, gcValues.stipple), 0},
    {TK_CONFIG_CUSTOM, "-fillstyle", "fillstyle", "FillStyle", "solid",
	Tk_Offset(DrawEnvironment, gcValues.fill_style),
	TK_CONFIG_DONT_SET_DEFAULT,
	&FillStyleOption },
    {TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL,
	(char *) NULL, 0, 0},
    {TK_CONFIG_SYNONYM, "-fg", "foreground", (char *) NULL,
	(char *) NULL, 0, 0},
    {TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL,
	(char *) NULL, 0, 0}
};

int
GetFgPixel(Tcl_Interp* interp,
	   Tk_Raster* rasterptr,
	   int index)
{
    DrawEnvironment* drawEnv;
    Raster* RasterPtr = (Raster*) rasterptr;

    if (DrawEnvIndex (interp, RasterPtr, index,
		      (ClientData*) &drawEnv) != TCL_OK) {
	return -1;
    }
    return drawEnv->gcValues.foreground;
}


int GetBgPixel(Tk_Raster* rasterptr)
{
    Raster* RasterPtr = (Raster*) rasterptr;
    return (Tk_3DBorderColor(RasterPtr->bgBorder)->pixel);
}

int
SetFgPixel(Tcl_Interp* interp,
	   Tk_Raster* rasterptr,
	   int index,
	   int fg_pixel)
{
    DrawEnvironment* drawEnv;
    Raster* RasterPtr = (Raster*) rasterptr;

    if (DrawEnvIndex (interp, RasterPtr, index,
		      (ClientData*) &drawEnv) != TCL_OK) {
	return -1;
    }
    drawEnv->gcValues.foreground = fg_pixel;
    return 0;
}

static int ConfigDrawEnv (interp, RasterPtr, drawEnv, argc, argv)
/*         -------------
 *
 *  Processes configuration options related to Drawing Environments.
 *  valMask and gcValues entries in the given DrawEnviroment structure
 *  are modified according to the configuration options. Returns
 *  a standard Tcl result.
 */
     Tcl_Interp* interp;
     Raster* RasterPtr;
     DrawEnvironment* drawEnv;
     int argc;
     char * argv [];
{
   if (Tk_ConfigureWidget(interp, RasterPtr->tkwin, DrawEnvSpecs,
      argc, argv, (char *) drawEnv, TK_CONFIG_ARGV_ONLY) != TCL_OK) {
      return TCL_ERROR;
   }

   if (drawEnv->bgColor) {
      /* Background was changed */
      drawEnv->valMask |= GCBackground;
      drawEnv->gcValues.background = drawEnv->bgColor->pixel;
   }
   if (drawEnv->fgColor) {
      /* Foreground was changed */
      drawEnv->valMask |= GCForeground;
      drawEnv->gcValues.foreground = drawEnv->fgColor->pixel;
   }
   if (DrawEnvSpecs [4].specFlags & TK_CONFIG_OPTION_SPECIFIED) {
      /* Line width was changed */
      drawEnv->valMask |= GCLineWidth;
   }
   if (DrawEnvSpecs [5].specFlags & TK_CONFIG_OPTION_SPECIFIED) {
      /* Line width was changed */
      drawEnv->valMask |= GCLineStyle;
   }
   if (DrawEnvSpecs [6].specFlags & TK_CONFIG_OPTION_SPECIFIED) {
      /* Cap Style was changed */
      drawEnv->valMask |= GCCapStyle;
   }
    if (DrawEnvSpecs [7].specFlags & TK_CONFIG_OPTION_SPECIFIED) {
      /* Join Style was changed */
      drawEnv->valMask |= GCJoinStyle;
   }
   if (DrawEnvSpecs [8].specFlags & TK_CONFIG_OPTION_SPECIFIED) {
      /* BITBLT function was changed */
      drawEnv->valMask |= GCFunction;
   }
   if (DrawEnvSpecs [9].specFlags & TK_CONFIG_OPTION_SPECIFIED) {
      /* Stipple bitmap was changed */
      drawEnv->valMask |= GCStipple;
   }
   if (DrawEnvSpecs [10].specFlags & TK_CONFIG_OPTION_SPECIFIED) {
      /* FillStyle was changed */
      drawEnv->valMask |= GCFillStyle;
   }
   
   drawEnv->drawGC = XCreateGC(RasterPtr->display, 
	                      RootWindowOfScreen(Tk_Screen (RasterPtr->tkwin)),
			              drawEnv->valMask, &(drawEnv->gcValues));

   if (drawEnv == RasterPtr->currentDrawEnv) {
      return SetDrawEnv (interp, RasterPtr, drawEnv);
   }

   return TCL_OK;
}

/* removed static kfs 10.05.00 */
int ConfigInfoDrawEnv (Tcl_Interp* interp,
		       Tk_Raster* raster,
		       DrawEnvironment*drawEnv,
		       int argc,
		       char **argv)
/*         -----------------
 *
 *  Returns a string describing configuration options of a drawing
 *  environment.
 */
{
    Raster* RasterPtr = (Raster*) raster;

   if (argc == 0) {
      return Tk_ConfigureInfo (interp, RasterPtr->tkwin,
			       DrawEnvSpecs, (char*) drawEnv, (char*)NULL, 0);
   }
   return Tk_ConfigureInfo (interp, RasterPtr->tkwin,
			    DrawEnvSpecs, (char*)drawEnv, argv [0], 0);
}

int DrawEnvIndex (interp, rasterptr, drawenvno, drawenvptrptr)
/*  ------------
 *
 *  Searches rasterptr's drawEnvTable for a DrawEnv for a drawing environment
 *  with the given 'drawenvno'. If successful, puts in *drawenvptr a pointer
 *  to that DrawEnv. Returns a standard TCL result
 */
     Tcl_Interp * interp;
     Tk_Raster* rasterptr;
     int drawenvno;
     ClientData* drawenvptrptr;
{
   Raster* RasterPtr = (Raster*) rasterptr;
   DrawEnvironment** drawEnvPtrPtr = (DrawEnvironment**) drawenvptrptr;
   Tcl_HashEntry *entryPtr;

   entryPtr = Tcl_FindHashEntry (&(RasterPtr->drawEnvTable), (char*)drawenvno);
   if (entryPtr == NULL) {
      Tcl_AppendResult (interp, "Given drawing environment does not exist",
			(char*) NULL);
      return TCL_ERROR;
   }
   *drawEnvPtrPtr = (DrawEnvironment*) Tcl_GetHashValue (entryPtr);
   return TCL_OK;
}


void GetDrawEnv (rasterptr, drawenvptr)
/*   ----------
 *
 *  Returns in * drawenvptr a pointer to the raster's current drawing env
 *
 */
     Tk_Raster* rasterptr;
     ClientData* drawenvptr;
{
   *drawenvptr = (ClientData)((Raster*) rasterptr)->currentDrawEnv;
}

int SetDrawEnv (interp, rasterptr, drawenvptr)
/*  ----------
 *
 *  Change the 'drawGC' of 'rasterptr' to reflect the drawing environment
 *  given by drawenvptr.
 *
 */
     Tcl_Interp * interp;
     Tk_Raster* rasterptr;
     ClientData drawenvptr;
{
   Raster* RasterPtr = (Raster*) rasterptr;
   DrawEnvironment* drawEnvPtr = (DrawEnvironment*) drawenvptr;

   if (drawEnvPtr->valMask != 0) {
        RasterPtr->drawGC = drawEnvPtr->drawGC;
   }

   RasterPtr->currentDrawEnv = drawEnvPtr;

   return TCL_OK;
}


static int CreateDrawEnv (interp, RasterPtr, argc, argv)
/*  -------------
 *
 *  Creates a new drawing environment for the given raster, setting it
 *  according to the options given in argc and argv. If successful,
 *  a pointer to the just created drawing environment is put in *drawenvptrptr.
 *  Returns a standard tcl result
 *
 */
     Tcl_Interp * interp;
     Raster* RasterPtr;
     int argc;
     char* argv [];
{
   Tcl_HashEntry *entryPtr;
   DrawEnvironment *drawEnvPtr;
   int new;

   drawEnvPtr = (DrawEnvironment*) malloc (sizeof (DrawEnvironment));
   drawEnvPtr->index = RasterPtr->drawEnvCount;
   drawEnvPtr->fgColor = Tk_GetColor (interp, RasterPtr->tkwin, "brown");
   drawEnvPtr->bgColor = Tk_GetColor (interp, RasterPtr->tkwin, "#d9d9d9");
   drawEnvPtr->gcValues.background = drawEnvPtr->bgColor->pixel;
   drawEnvPtr->gcValues.foreground = drawEnvPtr->fgColor->pixel;
   drawEnvPtr->gcValues.stipple = None;
   drawEnvPtr->gcValues.line_width = 1;
   drawEnvPtr->gcValues.line_style = LineSolid;
   drawEnvPtr->gcValues.cap_style = CapButt;
   drawEnvPtr->gcValues.fill_style = FillSolid;
   drawEnvPtr->gcValues.join_style = JoinRound;
   drawEnvPtr->gcValues.function = GXcopy;
   drawEnvPtr->valMask = (GCBackground|GCForeground|GCLineWidth|
			  GCLineStyle|GCCapStyle|GCJoinStyle|
			  GCFunction|GCFillStyle);
   if (ConfigDrawEnv (interp, RasterPtr, drawEnvPtr, argc, argv) != TCL_OK) {
      free (drawEnvPtr);
      return TCL_ERROR;
   }

   entryPtr = Tcl_CreateHashEntry (&(RasterPtr->drawEnvTable),
				   (char*) (RasterPtr->drawEnvCount),
				   &new);

   if (!new) {
      Tcl_AppendResult (interp, "Could not create a Drawing Environment",
			(char*)NULL);
      free (drawEnvPtr);
      return TCL_ERROR;
   }

   Tcl_SetHashValue (entryPtr, drawEnvPtr);

   vTcl_SetResult(interp, "%d", RasterPtr->drawEnvCount++);
   return TCL_OK;
}

static void DestroyDrawEnv (RasterPtr, drawenvptr)
/*          --------------
 *
 * Destroys the given drawing environment freeing its options
 */
     Raster* RasterPtr;
     DrawEnvironment*  drawenvptr;
{
   Tcl_HashEntry *entryPtr;
   Tk_FreeOptions (DrawEnvSpecs, (char*) drawenvptr, RasterPtr->display, 0);

   entryPtr = Tcl_FindHashEntry (&(RasterPtr->drawEnvTable),
				 (char*)(drawenvptr->index));
   Tcl_DeleteHashEntry (entryPtr);
   free (drawenvptr);
}

/*========================================================================
 *
 *  Procedures myOptionParse and myOptionPrint implement all custom options
 *  used for configuring drawing environments.
 *
 */

static int
myOptionParse (clientData, interp, tkwin, value, widgRec, offset)
     ClientData clientData;
     Tcl_Interp * interp;
     Tk_Window tkwin;
     char* value;
     char* widgRec;
     int offset;
{
   AttrNameValue* table = (AttrNameValue*) clientData;
   AttrNameValue* ptr = table;

   while (ptr->optionname != (char*) NULL) {
      if (strcmp (value, ptr->optionname) == 0) {
	 * (int *) (widgRec+offset) = ptr->optionvalue;
	 return TCL_OK;
      }
      ptr++;
   }

   Tcl_AppendResult (interp, "wrong arg \"",
		     value, "\": should be one of ", (char*) NULL);

   ptr = table;
   while (ptr->optionname != (char*)NULL) {
      Tcl_AppendResult (interp, "\"", ptr->optionname,
			(ptr+1)->optionname == (char*)NULL ? "\"." : "\",",
			(char*) NULL);
      ptr++;
   }

   return TCL_ERROR;
}

static char *
myOptionPrint (clientData, tkwin, widgRec, offset, freeProcPtr)
     ClientData clientData;
     Tk_Window tkwin;
     char* widgRec;
     int offset;
     Tcl_FreeProc ** freeProcPtr;
{
   AttrNameValue* ptr = (AttrNameValue*) clientData;
   int value = *(int*) (widgRec+offset);
   while (ptr->optionname != (char*)NULL) {
      if (ptr->optionvalue == value) return ptr->optionname;
      ptr++;
   }
   return (char*) NULL;
}

/*======================================================================
 *
 *  Utility functions for handling world-to-raster-and-back  transformations
 */

void SetRasterCoords (Tk_Raster* raster,
		      double x0,
		      double y0,
		      double x1,
		      double y1)
/*
 *  (x0,y0) are the coordinates of the upper-left corner and
 *  (x1,y1) are the coordinates of the lower-right corner
 */
{
   Raster* RasterPtr = (Raster*) raster;

   /* prevent any assignments if values are both 0 */
   if ((x1 - x0 == 0) || (y1-y0 == 0))
       return;

   RasterPtr->ax = RasterPtr->width / (x1-x0);
   RasterPtr->ay = RasterPtr->height / (y1-y0);

/*
   printf("SetRasterCoords width %d height %d \n", RasterPtr->width,
	  RasterPtr->height);
*/
#ifdef KFS_REMOVED
   double ratio;

   ratio = RasterPtr->ax / RasterPtr->ay;
   if (ratio < 0.0) ratio = -ratio;
   if (ratio > 1.0) {
      RasterPtr->ax /= ratio;
      RasterPtr->bx = x0 - (RasterPtr->width / RasterPtr->ax + x0 - x1) / 2;
      RasterPtr->by = y0;
   }
   else {
      RasterPtr->ay *= ratio;
      RasterPtr->bx = x0;
      RasterPtr->by = y0 - (RasterPtr->height / RasterPtr->ay + y0 - y1) / 2;
   }
#endif
   /* KFS: must set bx and by */
   RasterPtr->bx = x0;
   RasterPtr->by = y0;

   RasterPtr->wx0 = x0;
   RasterPtr->wy0 = y0;
   RasterPtr->wx1 = x1;
   RasterPtr->wy1 = y1;

#ifdef DEBUG
   printf("*******SetRasterCoords x0 %f x1 %f y0 %f y1 %f\n", x0, x1, y0, y1);
   printf("set to *%f+%f\n", RasterPtr->ax, RasterPtr->bx);
   printf("set to *%f+%f\n", RasterPtr->ay, RasterPtr->by);
#endif
}

void GetWorldToRasterConversion(Tk_Raster *raster, double *ax, double *ay, double *bx, double *by) {
/*
 * get the conversion factors for use outside
 * for speed rather than anything else
 */
    Raster* RasterPtr = (Raster*) raster;
    *ax = RasterPtr->ax;
    *ay = RasterPtr->ay;
    *bx = RasterPtr->bx;
    *by = RasterPtr->by;
}     


void WorldToRaster (raster, wx, wy, rx, ry)
/*
 *  (wx,wy) are  world coordinates
 *  (*rx,*ry) are set to the corresponding raster coordinates
 */
     Tk_Raster * raster;
     double wx, wy;
     int * rx, * ry;
{
   Raster* RasterPtr = (Raster*) raster;

    *rx = (wx - RasterPtr->bx) * RasterPtr->ax;
    *ry = (wy - RasterPtr->by) * RasterPtr->ay;
#ifdef DEBUG
   printf("WorldToRaster ax %f bx %f ay %f by %f wx %f wy %f rx %d ry %d\n",
	  RasterPtr->ax, RasterPtr->bx, RasterPtr->ay, RasterPtr->by, wx, wy,
	  *rx, *ry);
#endif
}

void RasterToWorld (raster, rx, ry, wx, wy)
/*
 *  (rx,ry) are raster coordinates
 *  (*wx,*wy) are set to the corresponding world coordinates
 */
     Tk_Raster* raster;
     int rx, ry;
     double * wx, * wy;
{
   Raster* RasterPtr = (Raster*) raster;

   *wx = rx / RasterPtr->ax + RasterPtr->bx;
   *wy = ry / RasterPtr->ay + RasterPtr->by;
#ifdef DEBUG
   printf("ry %d ay %f by %f wy %f \n",
	  RasterPtr->height, ry, RasterPtr->ay, RasterPtr->by, *wy);
#endif
}

/*======================================================================
 *
 *  SetRasterModifiedArea may be used by primitive implementations
 *  to let the raster know what part of the pixmap was modified.
 *  If not called, raster will assume that all pixmap was modified.
 *  If implementing a raster command that does not actually modify the
 *  pixmap, this routine should be called with 0 0 0 0 as args.
 */

void SetRasterModifiedArea (raster, rx0, ry0, rx1, ry1)
     Tk_Raster* raster;
     int rx0, ry0;
     int rx1, ry1;
{
   Raster* RasterPtr = (Raster*) raster;
   int lw, tmp;

   if (rx0 > rx1) { tmp = rx0; rx0 = rx1; rx1 = tmp; }
   if (ry0 > ry1) { tmp = ry0; ry0 = ry1; ry1 = tmp; }
   RasterPtr->knownarea = 1;
   if (rx1 == 0 && rx0 == 0 && ry1 == 0 && ry0 == 0) return;

   lw = RasterPtr->currentDrawEnv->gcValues.line_width;
   rx0 -= lw; if (rx0 < 0) rx0 = 0;
   rx1 += lw; if (rx1 >= RasterPtr->width) rx1 = RasterPtr->width-1;
   ry0 -= lw; if (ry0 < 0) ry0 = 0;
   ry1 += lw; if (ry1 >= RasterPtr->height) ry1 = RasterPtr->height-1;

   if (rx0 < RasterPtr->px0) RasterPtr->px0 = rx0;
   if (ry0 < RasterPtr->py0) RasterPtr->py0 = ry0;
   if (rx1 > RasterPtr->px1) RasterPtr->px1 = rx1;
   if (ry1 > RasterPtr->py1) RasterPtr->py1 = ry1;
}

/*======================================================================
 *
 *  The following are utility functions to access elements of a Tk_Raster.
 *  They may be used to implement drawing primitives which have to
 *  access X functions directly
 */

Drawable GetRasterDrawable (raster)
     Tk_Raster* raster;
{
   return ((Raster*)raster)->pm;
}

Display* GetRasterDisplay (raster)
     Tk_Raster* raster;
{
   return ((Raster*)raster)->display;
}

Tk_Window GetRasterTkWin (raster)
     Tk_Raster* raster;
{
   return ((Raster*)raster)->tkwin;
}

GC GetRasterGC (raster)
     Tk_Raster* raster;
{
   return ((Raster*)raster)->drawGC;
}


/*=======================================================================
 *
 *  Below are the functions that implement the built-in drawing primitives
 */


void RasterDrawPoints (raster, coord, npts)
/*   ----------------
 *
 *  Draws the points (coord [2i], coord [2i+1]) for 0 <= i < npts
 */
    Tk_Raster * raster;
     double* coord;
     int npts;
{
   int pointwid = ((Raster*) raster)->currentDrawEnv->gcValues.line_width ;
   GC gc = GetRasterGC (raster);
   Drawable d = GetRasterDrawable (raster);
   Display * dsp = GetRasterDisplay (raster);
   int i;
   int n = 2 * npts;
   XPoint *pt, *ptptr;
   int rx, ry;
   int minx = HIGH, miny = HIGH, maxx = LOW, maxy = LOW;

   if (npts < 1) return;

   for (i = 0, ptptr = pt = (XPoint*) malloc (sizeof (XPoint)*npts);
	i < n; i+=2, ptptr++) {
      WorldToRaster (raster, coord [i], coord [i+1], &rx, &ry);
      if (rx < minx) minx = rx;
      if (rx > maxx) maxx = rx;
      if (ry < miny) miny = ry;
      if (ry > maxy) maxy = ry;
      ptptr->x = rx;
      ptptr->y = ry;
   }

   if (pointwid >= 2) {
      int halfwid = pointwid/2;
      for (i=0, ptptr = pt; i < npts; i++, ptptr++) {
	 XFillArc (dsp, d, gc, ptptr->x-halfwid, ptptr->y-halfwid,
		   pointwid, pointwid, 0, 360*64);
      }
   } else {
      XDrawPoints (dsp, d, gc, 	pt, npts, CoordModeOrigin);
   }
   free (pt);

   SetRasterModifiedArea (raster, minx, miny, maxx, maxy);
}

void RasterDrawPoint (Tk_Raster *raster,
		      int x,
		      int y)
/*   ---------------
 *
 *  Draws the point x, y
 */
{
   int pointwid = ((Raster*) raster)->currentDrawEnv->gcValues.line_width ;
   GC gc = GetRasterGC (raster);
   Drawable d = GetRasterDrawable (raster);
   Display * dsp = GetRasterDisplay (raster);
   int rx, ry;
   int minx = HIGH, miny = HIGH, maxx = LOW, maxy = LOW;

   WorldToRaster (raster, x, y, &rx, &ry);
   if (rx < minx) minx = rx;
   if (rx > maxx) maxx = rx;
   if (ry < miny) miny = ry;
   if (ry > maxy) maxy = ry;

   if (pointwid >= 2) {
      int halfwid = pointwid/2;
      XFillArc (dsp, d, gc, rx - halfwid, ry - halfwid,
		pointwid, pointwid, 0, 360*64);
   } else {
      XDrawPoint (dsp, d, gc, rx, ry);
   }

#ifdef DEBUG
   printf("x %d y %d rx %d ry %d \n", x, y, rx, ry);
#endif
   /* XDrawPoint (dsp, d, gc, rx, ry); */

   SetRasterModifiedArea (raster, minx, miny, maxx, maxy);
}

void
RasterDrawLine (Tk_Raster *raster,
		int x1, double y1, int x2, double y2)
/*   ---------------
 *
 *  Draws a single line segments connecting x1 y1 with x2 y2
 */
{
   int rx1, ry1, rx2, ry2;
   int minx = HIGH, miny = HIGH, maxx = LOW, maxy = LOW;

   WorldToRaster (raster, x1, y1, &rx1, &ry1);
   WorldToRaster (raster, x2, y2, &rx2, &ry2);

#ifdef DEBUG
   printf("line (%d,%f)-(%d,%f) [%d,%d]-[%d,%d]\n",
	  x1, y1, x2, y2,
	  rx1, ry1, rx2, ry2);
#endif
   if (rx1 < minx) minx = rx1;
   if (rx1 > maxx) maxx = rx1;
   if (ry1 < miny) miny = ry1;
   if (ry1 > maxy) maxy = ry1;

   if (rx2 < minx) minx = rx2;
   if (rx2 > maxx) maxx = rx2;
   if (ry2 < miny) miny = ry2;
   if (ry2 > maxy) maxy = ry2;

   XDrawLine (GetRasterDisplay (raster),
	      GetRasterDrawable (raster),
	      GetRasterGC (raster),
	      rx1, ry1, rx2, ry2);

   /* printf("minx %d miny %d maxx %d maxy %d\n", minx, miny, maxx, maxy); */
   SetRasterModifiedArea (raster, minx, miny, maxx, maxy);
}

void RasterDrawLines (raster, coord, npts)
/*   ---------------
 *
 *  Draws the npts-1 line segments connecting the successive
 *  'npts' points (coord [2i], coord [2i+1]), for 0 <= i < npts.
 */
     Tk_Raster * raster;
     double* coord;
     int npts;
{
   int i, j, num;
   int n = npts*2;
   XPoint *pt, *ptptr;
   int rx, ry;
   int minx = HIGH, miny = HIGH, maxx = LOW, maxy = LOW;

   if (npts < 1) return;

   for (i = 0, ptptr = pt = (XPoint*) malloc (sizeof (XPoint)*npts);
	i < n; i+=2, ptptr++) {
      WorldToRaster (raster, coord [i], coord [i+1], &rx, &ry);
      if (rx < minx) minx = rx;
      if (rx > maxx) maxx = rx;
      if (ry < miny) miny = ry;
      if (ry > maxy) maxy = ry;
      ptptr->x = rx;
      ptptr->y = ry;
   }

   /*
    * fix to deal with x servers which can't cope with more than 2^16 lines
    */
   if (npts < 65000) {
       XDrawLines (GetRasterDisplay (raster),
		   GetRasterDrawable (raster),
		   GetRasterGC (raster),
		   pt, npts, CoordModeOrigin);
   } else {
       j = 1;
       for (i = 0; i < npts; i+=65000, j = i) {
	   if (npts < i + 65000) {
	       num = npts - i + 1;
	   } else {
	       num = 65000;
	   }

	   XDrawLines (GetRasterDisplay (raster),
		       GetRasterDrawable (raster),
		       GetRasterGC (raster),
		       &pt[j-1], num, CoordModeOrigin);
       }
   }
   /*
   XDrawLines (GetRasterDisplay (raster),
	       GetRasterDrawable (raster),
	       GetRasterGC (raster),
	       pt, npts, CoordModeOrigin);
   */
   free (pt);

   SetRasterModifiedArea (raster, minx, miny, maxx, maxy);
}

void RasterDrawSegments (Tk_Raster * raster,
			 double* coord,
			 int nsegs)
/*   ---------------
 *
 *  Draws the nsegs line segments connecting pairs of successive
 *  points. coord contains nsegs*4 values.
 */
{
   int i, num;
   int n = nsegs*4;
   XSegment *seg, *segptr;
   int rx1, ry1, rx2, ry2;
   int minx = HIGH, miny = HIGH, maxx = LOW, maxy = LOW;

   if (nsegs < 1) return;

   for (i = 0, segptr = seg = (XSegment*) malloc (sizeof (XSegment)*(nsegs));
	i < n; i+=4, segptr++) {
      WorldToRaster (raster, coord [i], coord [i+1], &rx1, &ry1);
      WorldToRaster (raster, coord [i+2], coord [i+3], &rx2, &ry2);
      if (rx1 < minx) minx = rx1;
      if (rx1 > maxx) maxx = rx1;
      if (ry1 < miny) miny = ry1;
      if (ry1 > maxy) maxy = ry1;
      if (rx2 < minx) minx = rx2;
      if (rx2 > maxx) maxx = rx2;
      if (ry2 < miny) miny = ry2;
      if (ry2 > maxy) maxy = ry2;
      segptr->x1 = rx1;
      segptr->y1 = ry1;
      segptr->x2 = rx2;
      segptr->y2 = ry2;
   }

   /*
    * fix to deal with x servers which can't cope with more than 2^16 lines
    */
   if (nsegs < 32000) {
       XDrawSegments (GetRasterDisplay (raster),
		   GetRasterDrawable (raster),
		   GetRasterGC (raster),
		   seg, nsegs);
   } else {
       for (i = 0; i < nsegs; i+=32000) {
	   if (nsegs < i + 32000) {
	       num = nsegs - i;
	   } else {
	       num = 32000;
	   }

	   XDrawSegments (GetRasterDisplay (raster),
		       GetRasterDrawable (raster),
		       GetRasterGC (raster),
		       &seg[i], num);
       }
   }

   free (seg);

   SetRasterModifiedArea (raster, minx, miny, maxx, maxy);
}

void RasterDrawRectangles (raster, coord, nrects)
/*   --------------------
 *
 *  Draws rectangles with sides aligned with the coordinate axes and
 *  with diagonal corners at (coord [4i], coord [4i+1]) and
 *  (coord [4i+2], coord [4i+3]) for  0 <= i < nrects,
 */
     Tk_Raster * raster;
     double* coord;
     int nrects;
{
   int i;
   int n = nrects*4;
   XRectangle *rect, *rectptr;
   int rx, ry, tmp;
   int minx = HIGH, miny = HIGH, maxx = LOW, maxy = LOW;

   if (nrects < 1) return;

   for (i = 0, rectptr= rect= (XRectangle*) malloc(sizeof (XRectangle)*nrects);
	i < n; i+=4, rectptr++) {
      WorldToRaster (raster, coord [i], coord [i+1], &rx, &ry);
      if (rx < minx) minx = rx;
      if (rx > maxx) maxx = rx;
      if (ry < miny) miny = ry;
      if (ry > maxy) maxy = ry;
      rectptr->x = rx;
      rectptr->y = ry;
      WorldToRaster (raster, coord [i+2], coord [i+3], &rx, &ry);
      if (rx < minx) minx = rx;
      if (rx > maxx) maxx = rx;
      if (ry < miny) miny = ry;
      if (ry > maxy) maxy = ry;
      if (rectptr->x > rx) { tmp = rectptr->x; rectptr->x = rx; rx = tmp; }
      if (rectptr->y > ry) { tmp = rectptr->y; rectptr->y = ry; ry = tmp; }
      rectptr->width = rx - rectptr->x;
      rectptr->height = ry - rectptr->y;
   }

   XDrawRectangles (GetRasterDisplay (raster),
		    GetRasterDrawable (raster),
		    GetRasterGC (raster),
		    rect, nrects);
   free (rect);

   SetRasterModifiedArea (raster, minx, miny, maxx, maxy);
}

void RasterFillRectangles (raster, coord, nrects)
/*   --------------------
 *
 *  Draws filled rectangles with sides aligned with the coordinate axes and
 *  with diagonal corners at (coord [4i], coord [4i+1]) and
 *  (coord [4i+2], coord [4i+3]) for  0 <= i < nrects,
 */
     Tk_Raster * raster;
     double* coord;
     int nrects;
{
   int i;
   int n = nrects*4;
   XRectangle *rect, *rectptr;
   int rx, ry, tmp;
   int minx = HIGH, miny = HIGH, maxx = LOW, maxy = LOW;

   if (nrects < 1) return;

   for (i = 0, rectptr= rect= (XRectangle*) malloc(sizeof (XRectangle)*nrects);
	i < n; i+=4, rectptr++) {
      WorldToRaster (raster, coord [i], coord [i+1], &rx, &ry);
      if (rx < minx) minx = rx;
      if (rx > maxx) maxx = rx;
      if (ry < miny) miny = ry;
      if (ry > maxy) maxy = ry;
      rectptr->x = rx;
      rectptr->y = ry;
      WorldToRaster (raster, coord [i+2], coord [i+3], &rx, &ry);
      if (rx < minx) minx = rx;
      if (rx > maxx) maxx = rx;
      if (ry < miny) miny = ry;
      if (ry > maxy) maxy = ry;
      if (rectptr->x > rx) { tmp = rectptr->x; rectptr->x = rx; rx = tmp; }
      if (rectptr->y > ry) { tmp = rectptr->y; rectptr->y = ry; ry = tmp; }
      rectptr->width = rx - rectptr->x;
      rectptr->height = ry - rectptr->y;
   }

   XFillRectangles (GetRasterDisplay (raster),
		    GetRasterDrawable (raster),
		    GetRasterGC (raster),
		    rect, nrects);
   free (rect);

   SetRasterModifiedArea (raster, minx, miny, maxx, maxy);
}

void RasterFillPolygon (raster, coord, npts)
/*   -----------------
 *
 *  Fills the polygon bounded by the line segments connecting the successive
 *  'npts' points (coord [2i], coord [2i+1]), for 0 <= i < npts.
 *  If the last point is not equal to the first point, a line segment
 *  connecting them is added.
 */
     Tk_Raster * raster;
     double* coord;
     int npts;
{
   int i;
   int n = npts*2;
   XPoint *pt, *ptptr;
   int rx, ry;
   int minx = HIGH, miny = HIGH, maxx = LOW, maxy = LOW;

   if (npts < 1) return;

   for (i = 0, ptptr = pt = (XPoint*) malloc (sizeof (XPoint)*npts);
	i < n; i+=2, ptptr++) {
      WorldToRaster (raster, coord [i], coord [i+1], &rx, &ry);
      if (rx < minx) minx = rx;
      if (rx > maxx) maxx = rx;
      if (ry < miny) miny = ry;
      if (ry > maxy) maxy = ry;
      ptptr->x = rx;
      ptptr->y = ry;
   }

   XFillPolygon (GetRasterDisplay (raster),
		 GetRasterDrawable (raster),
		 GetRasterGC (raster),
		 pt, npts, Complex, CoordModeOrigin);
   free (pt);

   SetRasterModifiedArea (raster, minx, miny, maxx, maxy);
}

/*
 * C interface to tcl routine envcreate
 */
int
CreateDrawEnviron(Tcl_Interp *interp,
		  Tk_Raster *RasterPtr,
		  int argc, char **argv)
{
    int result;

    CreateDrawEnv(interp, RasterPtr, argc, argv);
    result = atoi(Tcl_GetStringResult(interp));
    return result;
}

/*
 * C interface to tcl routine envset
 */
int
SetDrawEnviron (Tcl_Interp *interp,
		Tk_Raster *RasterPtr,
		int index)
{
    int result;
    DrawEnvironment *drawEnvPtr;

    if (DrawEnvIndex (interp, RasterPtr, index,
		      (ClientData*)&drawEnvPtr) != TCL_OK){
#ifdef DEBUG
	printf("ERROR1: failed DrawEnvIndex\n");
#endif
	return -1;
    }
    result = SetDrawEnv (interp, RasterPtr, drawEnvPtr);
    return result;
}

char *
GetRasterColour (Tcl_Interp *interp,
		 Tk_Raster *RasterPtr,
		 int index)
{
    int result;
    DrawEnvironment *drawEnvPtr;
    static char colour[10];

    if (DrawEnvIndex (interp, RasterPtr, index,
		      (ClientData*)&drawEnvPtr) != TCL_OK){
#ifdef DEBUG
	printf("ERROR2: failed DrawEnvIndex %d\n", index);
#endif
    }
    result = SetDrawEnv (interp, RasterPtr, drawEnvPtr);
    sprintf(colour, "#%02x%02x%02x", drawEnvPtr->fgColor->red/256,
	    drawEnvPtr->fgColor->green/256, drawEnvPtr->fgColor->blue/256);
    return colour;
}

int GetRasterLineWidth (Tcl_Interp *interp,
		       Tk_Raster *RasterPtr,
		       int index)
{
    int result;
    DrawEnvironment *drawEnvPtr;

    if (DrawEnvIndex (interp, RasterPtr, index,
		      (ClientData*)&drawEnvPtr) != TCL_OK){

    }
    result = SetDrawEnv (interp, RasterPtr, drawEnvPtr);

    return (drawEnvPtr->gcValues.line_width);
}


static void
RasterClear(Raster *RasterPtr)
{
    if (RasterPtr->plot_func) {
	RasterPtr->plot_func(RasterPtr, Tk_PathName(RasterPtr->tkwin),
			     RASTER_INIT, 0, 0, 0, 0);
    }

    /* set the crosshair flag to be "not visible" */
    Tcl_VarEval(RasterPtr->interp, "unset_raster_xh ",
		Tk_PathName(RasterPtr->tkwin), NULL);
    XFillRectangle (RasterPtr->display, RasterPtr->pm, RasterPtr->copyGC,
		       0, 0, RasterPtr->width, RasterPtr->height);
    arrangeDisplay (RasterPtr, LOW, LOW, HIGH, HIGH, RASTER_DRAW_PIXMAP);
}

void
tk_RasterClear(Tk_Raster *rasterptr)
{
    Raster* RasterPtr = (Raster*) rasterptr;

    RasterClear(RasterPtr);
}

void
RasterClearArea(Raster *RasterPtr,
		int x0,	int y0, int x1, int y1)
{

    XFillRectangle (RasterPtr->display, RasterPtr->pm, RasterPtr->copyGC,
		       x0, y0, x1, y1);
    arrangeDisplay (RasterPtr, LOW, LOW, HIGH, HIGH, RASTER_DRAW_PIXMAP);

}

void GetRasterCoords(Tk_Raster *rasterptr,
		     double *wx0,
		     double *wy0,
		     double *wx1,
		     double *wy1)
{
    Raster* raster = (Raster*) rasterptr;

    *wx0 = raster->wx0;
    *wy0 = raster->wy0;
    *wx1 = raster->wx1;
    *wy1 = raster->wy1;
}

static void
RasterScrollX(Raster *raster,
	      int new_x, /* pixel coords */
	      int old_x) /* pixel coords */
{
    double max_x, min_x;
    double wx0, wx1;
    double wnew_x, wold_x, wnew_y, wold_y;
    double dx;

    /* find the portion of the raster (left or right) to be replotted */
    RasterToWorld(raster, new_x-old_x, 0, &wnew_x, &wnew_y);
    RasterToWorld(raster, 0, 0, &wold_x, &wold_y);

    min_x = raster->wx0; /* min world base on raster */
    max_x = raster->wx1; /* max world base on raster */
    dx = wnew_x - wold_x; /* amount of scrolling */
    if (dx > 0) {
	/* fill right edge */
	wx1 = max_x + dx;
	if (dx > max_x - min_x)
	    wx0 = min_x + dx;
	else
	    wx0 = max_x;
    } else {
	/* fill left edge */
	wx0 = min_x + dx;
	if (-dx > max_x - min_x)
	    wx1 = max_x + dx;
	else
	    wx1 = min_x;
    }

#ifdef SCROLL
    printf("woldx %f wnewx %f dx %f wx0 %f wx1 %f max_x %f min_x %f\n", wold_x, wnew_x, dx, wx0, wx1, max_x, min_x);
    printf("raster->wx0=%f,dx=%f, +=%f\n",
	   raster->wx0, dx, raster->wx0+dx);
#endif
    /*
     * set up new world coords so that the replotting results appear in the
     * correct place
     */
    SetRasterCoords (raster, wnew_x, raster->wy0,
		     wnew_x + (raster->wx1 - raster->wx0), raster->wy1);

#ifdef SCROLL
/*    printf("SetRasterCoords wx0 %f wx1 %f\n", wx0, wx1);*/
#endif
    if (raster->plot_func) {
	raster->plot_func(raster, Tk_PathName(raster->tkwin),
			  RASTER_REPLOT_SLIVER,
			  (int)wx0, 0, (int)(wx1+1), 0);
    }
}

static void
RasterScrollY(Raster *raster,
	      int new_y, /* pixel coords */
	      int old_y) /* pixel coords */
{
    double max_y, min_y;
    double wy0, wy1;
    double wnew_x, wold_x, wnew_y, wold_y;
    double dy = 0;

    /* find the portion of the raster (top or bottom) to be replotted */
    RasterToWorld(raster, 0, new_y-old_y, &wnew_x, &wnew_y);
    RasterToWorld(raster, 0, 0, &wold_x, &wold_y);

    min_y = raster->wy0; /* min world base on raster */
    max_y = raster->wy1; /* max world base on raster */
    dy = wnew_y - wold_y; /* amount of scrolling */
    if (dy < 0) {
	/* fill top edge */
	wy0 = min_y;
	wy1 = min_y + dy;
    } else {
	/* fill bottom edge */
	wy0 = max_y;
	wy1 = max_y + dy;
    }

#ifdef SCROLL
    printf("woldy %f wnewy %f dy %f wy0 %f wy1 %f max_y %f min_y %f\n", wold_y, wnew_y, dy, wy0, wy1, max_y, min_y);
    printf("raster->wy0=%f,dy=%f, +=%f\n",
	   raster->wy0, dy, raster->wy0+dy);
#endif

    /*
     * set up new world coords so that the replotting results appear in the
     * correct place
     */
    SetRasterCoords (raster, raster->wx0, wnew_y,
		     raster->wx1, wnew_y + (raster->wy1 - raster->wy0));

#ifdef SCROLL
    printf("SetRasterCoords wy0 %f wy1 %f\n", wy0, wy1);
    printf("start %f end %f \n", raster->wy_start, raster->wy_end);

#endif
    /*
     * because we display the results "upside down", need to subtract the
     * max y in world coords. Need to add 1 because I plot to max y + 1
     */
    if (raster->plot_func) {
	raster->plot_func(raster, Tk_PathName(raster->tkwin),
			  RASTER_REPLOT_ALL,
			  (int)raster->wx0,
			  (int)(raster->wy_end - wy0)+1,
			  (int)raster->wx1, (int)(raster->wy_end - wy1) + 2);
    }
}

void RasterResetWorldScroll(Tk_Raster *rasterptr)
{
    Raster* raster = (Raster*) rasterptr;

#ifdef DEBUG
    printf("RasterResetWorldScroll\n");
#endif

    raster->wx_start = DBL_MAX/2;
    raster->wy_start = DBL_MAX/2;
    raster->wx_end = -DBL_MAX/2;
    raster->wy_end = -DBL_MAX/2;
}


/*
 * set the scroll region for a single raster
 * return 1 if the scroll region was changed, else return 0
 */
int
RasterSetWorldScroll(Tk_Raster *rasterptr,
		     double x0, double y0,
		     double x1, double y1)
{
    Raster* raster = (Raster*) rasterptr;
    int flag = 0;

#ifdef DEBUG
    printf("RasterSetWorldScroll %s x0 %f x1 %f wx0 %f wx1 %f\n",
	   Tk_PathName(raster->tkwin), x0, x1, raster->wx_start, raster->wx_end);
    printf("RasterSetWorldScroll y0 %f y1 %f wy0 %f wy1 %f\n",
	   y0, y1, raster->wy_start, raster->wy_end);
#endif

    if (x0 != raster->wx_start) {
	raster->wx_start = x0;
	flag = 1;
    }
    if (y0 != raster->wy_start) {
	raster->wy_start = y0;
	flag = 1;
    }
    if (x1 != raster->wx_end) {
	raster->wx_end = x1;
	flag = 1;
    }
    if (y1 != raster->wy_end) {
	raster->wy_end = y1;
	flag = 1;
    }

    /*
     * need some checks here to ensure that the start and ends are never
     * the identical for the same direction which could lead to a divide
     * by 0 error
     */

    if (raster->wx_start == raster->wx_end) {
	raster->wx_start -= 1e-10;
	raster->wx_end += 1e-10;
    }

    if (raster->wy_start == raster->wy_end) {
	raster->wy_start -= 1e-10;
	raster->wy_end += 1e-10;
    }

#ifdef DEBUG
    printf("RasterSetWorldScroll %s x0 %f x1 %f y0 %f y1 %f \n",
	   Tk_PathName(raster->tkwin), raster->wx_start, raster->wx_end,
	   raster->wy_start, raster->wy_end);
#endif

    return flag;
}

void
RasterGetWorldScroll(Tk_Raster *rasterptr,
		     double *x0, double *y0,
		     double *x1, double *y1)
{
    Raster* raster = (Raster*) rasterptr;

    *x0 = raster->wx_start;
    *y0 = raster->wy_start;
    *x1 = raster->wx_end;
    *y1 = raster->wy_end;

#ifdef DEBUG
    printf("RasterGetWorldScroll %s %f %f %f %f \n",
	   Tk_PathName(raster->tkwin), *x0, *y0, *x1, *y1);
#endif
}

void
RasterWinSize(Tk_Raster *rasterptr,
	      int *width, int *height)
{
    Raster* raster = (Raster*) rasterptr;

    *width = raster->width;
    *height = raster->height;
}

void
RasterInitPlotFunc(Tk_Raster *rasterptr,
		   void (*plot_func)(Tk_Raster *raster, char *raster_win,
				     int job, int x0, int y0, int x1,
				     int y1))
{

    Raster* raster = (Raster*) rasterptr;
    raster->plot_func = plot_func;
}

void RasterDeletePlotFunc(Tk_Raster *rasterptr)
{

    Raster* raster = (Raster*) rasterptr;
    raster->plot_func = NULL;
}

/*
 * find the new_range given an old_range and a mag value
 * from a scale range of say, 1 to 100, a value of 1 gives a mag of 100/100,
 * a value of 2 gives 99/100 and a value of 100 depicts 10 bases
 * using: scale_min   old_range
 *        scale_max   min_bases
 *  scale_min = m * old_range + c
 *  scale_max = m * min_bases + c
 */
double RasterSetXMag(Tcl_Interp *interp,
		     double old_range,
		     int value)
{
    double m, c;
    double new_range;
    int scale_min, scale_max;
    int min_bases;

    scale_min = get_default_int(interp, tk_utils_defs, "RASTER.SCALEX.MIN");
    scale_max = get_default_int(interp, tk_utils_defs, "RASTER.SCALEX.MAX");
    min_bases = get_default_int(interp, tk_utils_defs, "RASTER.SCALEX.MIN_BASES");

    m = (old_range - min_bases) / (scale_min - scale_max);
    c = min_bases - (m * scale_max);
    new_range = m * value + c;

#ifdef DEBUG
    printf("RasterSetXMag value %d old %f min_bases %d m %f c %f new %f\n",
	   value, old_range, min_bases, m, c, new_range);
#endif
    return new_range;
}

/*
 * find the mag value to convert old_range into new_range
 */
double RasterGetXMag(Tcl_Interp *interp,
		     double old_range,
		     double new_range)
{
    int scale_min, scale_max;
    double value;
    double m, c;
    int min_bases;

    scale_min = get_default_int(interp, tk_utils_defs, "RASTER.SCALEX.MIN");
    scale_max = get_default_int(interp, tk_utils_defs, "RASTER.SCALEX.MAX");
    min_bases = get_default_int(interp, tk_utils_defs, "RASTER.SCALEX.MIN_BASES");

    m = (old_range - min_bases) / (scale_min - scale_max);
    c = min_bases - (m * scale_max);
    value = (new_range - c) / m;
    return value;
}

double RasterSetYMag(Tcl_Interp *interp,
		     double old_range,
		     int value)
{
    double new_range;
    int scale_min, scale_max;
    int scale_range;

    scale_min = get_default_int(interp, tk_utils_defs, "RASTER.SCALEY.MIN");
    scale_max = get_default_int(interp, tk_utils_defs, "RASTER.SCALEY.MAX");

    scale_range = scale_max - scale_min + 1;
    /* percentage decrement */
    new_range = (double)(scale_range - value + 1) / scale_range * old_range;
#ifdef DEBUG
    printf("RasterSetYMag: scale %d value %d old %f new %f\n", scale_range, value,
	   old_range, new_range);
#endif
    return new_range;
}

double RasterGetYMag(Tcl_Interp *interp,
		     double old_range,
		     double new_range)
{
    double value;
    int scale_min, scale_max;
    int scale_range;

    scale_min = get_default_int(interp, tk_utils_defs, "RASTER.SCALEY.MIN");
    scale_max = get_default_int(interp, tk_utils_defs, "RASTER.SCALEY.MAX");
    scale_range = scale_max - scale_min + 1;

    value = scale_range - (new_range * scale_range / old_range) + 1;

#ifdef DEBUG
    printf("RasterGetYMag old %f new %f value %f\n", old_range, new_range, value);
#endif
    return value;
}

void RasterCallPlotFunc(Tk_Raster *rasterptr,
			int job,
			int x0, int y0, int x1, int y1)
{
    Raster* raster = (Raster*) rasterptr;

    if (raster->plot_func) {
	raster->plot_func(raster, Tk_PathName(raster->tkwin), job, x0, y0, x1, y1);
    }
}